- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathlesson07_stop_thread.py
More file actions
Latest commit
34 lines (32 loc) · 913 Bytes
/
Copy pathlesson07_stop_thread.py
File metadata and controls
34 lines (32 loc) · 913 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
26
27
28
29
30
31
32
33
34
# SuperFastPython.com
# example of stopping a new thread gracefully
fromtimeimportsleep
fromthreadingimportThread
fromthreadingimportEvent
# custom function to be executed in a new thread
deftask(shared_event):
# execute a task in a loop
for_inrange(5):
# block for a moment
sleep(1)
# check for stop
ifshared_event.is_set():
break
# report a message
print('Worker thread running...')
print('Worker closing down')
# protect the entry point
if__name__=='__main__':
# create the shared event
event=Event()
# create and configure a new thread
thread=Thread(target=task, args=(event,))
# start the new thread
thread.start()
# block for a while
sleep(3)
# stop the worker thread
print('Main stopping thread')
event.set()
# wait for the new thread to finish
thread.join()