- Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlesson06_asyncresult.py
More file actions
Latest commit
32 lines (30 loc) · 1.04 KB
/
Copy pathlesson06_asyncresult.py
File metadata and controls
32 lines (30 loc) · 1.04 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
# SuperFastPython.com
# example check status and handle result of async task
fromtimeimportsleep
fromrandomimportrandom
frommultiprocessingimportPool
# custom function to be executed in a child process
deftask():
# loop a few times to simulate a slow task
foriinrange(10):
# generate a random value between 0 and 1
value=random()
# block for a fraction of a second
sleep(value)
# report a message
print(f'>{i} got {value}', flush=True)
# protect the entry point
if__name__=='__main__':
# create the multiprocessing pool
withPool() aspool:
# issue a task asynchronously
async_result=pool.apply_async(task)
# wait until the task is complete
whilenotasync_result.ready():
# report a message
print('Main process waiting...')
# block for a moment
async_result.wait(timeout=1)
# report if the task was successful
ifasync_result.successful():
print('Task was successful.')