- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlesson05_future_cancel.py
More file actions
Latest commit
25 lines (23 loc) · 807 Bytes
/
Copy pathlesson05_future_cancel.py
File metadata and controls
25 lines (23 loc) · 807 Bytes
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
# SuperFastPython.com
# example of canceling a task via it's future
fromtimeimportsleep
fromconcurrent.futuresimportThreadPoolExecutor
# custom function executed in a worker thread
defwork(sleep_time):
# block for a moment
sleep(sleep_time)
# protect the entry point
if__name__=='__main__':
# create a thread pool
withThreadPoolExecutor(1) asexe:
# start a long running task
future1=exe.submit(work, 2)
running=future1.running()
print(f'First task running={running}')
# start a second
future2=exe.submit(work, 0.1)
running=future2.running()
print(f'Second task running={running}')
# cancel the second task
canceled=future2.cancel()
print(f'Second task was canceled: {canceled}')