- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlesson03_timeout.py
More file actions
Latest commit
32 lines (30 loc) · 1.02 KB
/
Copy pathlesson03_timeout.py
File metadata and controls
32 lines (30 loc) · 1.02 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 of executing tasks concurrently with timeout
fromrandomimportrandom
fromtimeimportsleep
fromconcurrent.futuresimportThreadPoolExecutor
fromconcurrent.futuresimportTimeoutError
# custom function to be executed in a worker thread
deftask(number):
# generate a random value between 0 and 1
value=random()
# report a message
print(f'Task generated {value}')
# block for a moment to simulate work
sleep(number+value)
# return a new value
returnnumber+value
# protect the entry point
if__name__=='__main__':
# create the thread pool
withThreadPoolExecutor(4) asexe:
try:
# issue tasks to execute concurrently
forresultinexe.map(task, range(10),
timeout=2):
# report results
print(result)
exceptTimeoutError:
print('Gave up, took too long')
# report that we will wait for the tasks to complete
print('Waiting for tasks to complete...')