- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlesson06_wait_error.py
More file actions
Latest commit
38 lines (36 loc) · 1.26 KB
/
Copy pathlesson06_wait_error.py
File metadata and controls
38 lines (36 loc) · 1.26 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
32
33
34
35
36
37
38
# SuperFastPython.com
# example of waiting for the first task to fail
fromtimeimportsleep
fromrandomimportrandom
fromconcurrent.futuresimportProcessPoolExecutor
fromconcurrent.futuresimportwait
fromconcurrent.futuresimportFIRST_EXCEPTION
# custom task function executed by a worker process
deftask(number):
# generate a random number between 0 and 1
value=random()
# block for a fraction of a second
sleep(value)
# check for a failure
ifvalue<0.5:
raiseException(f'Task {number} Failed')
# report that the task completed
print(f'>task {number} is done', flush=True)
# return the task number
returnnumber
# protect the entry point
if__name__=='__main__':
# start the process pool
withProcessPoolExecutor(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_EXCEPTION)
# check that no tasks failed
iflen(done) ==len(futs):
print('No tasks failed')
else:
# get the first task to complete
future=done.pop()
# report the exception
print(f'First fail: {future.exception()}')