- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlesson06_wait_first.py
More file actions
Latest commit
31 lines (29 loc) · 1.03 KB
/
Copy pathlesson06_wait_first.py
File metadata and controls
31 lines (29 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# SuperFastPython.com
# example of waiting for the first task to complete
fromtimeimportsleep
fromrandomimportrandom
fromconcurrent.futuresimportThreadPoolExecutor
fromconcurrent.futuresimportwait
fromconcurrent.futuresimportFIRST_COMPLETED
# custom task function executed by a worker thread
deftask(number):
# block for a fraction of a second
sleep(random())
# report that the task completed
print(f'>task {number} is done')
# return the task number
returnnumber
# protect the entry point
if__name__=='__main__':
# start the thread pool
withThreadPoolExecutor(10) asexe:
# submit tasks and collect futures
futs= [exe.submit(task, i) foriinrange(10)]
# wait until any task completes
done,_=wait(futs, return_when=FIRST_COMPLETED)
# get the first task to complete
future=done.pop()
# get the result from the first task to complete
result=future.result()
# report the result
print(f'Main first result: {result}')