A similar question is "How do you kill a thread?"
You create an exit handler in your thread that is controlled by a lock or event object from the threading module. You then simply remove the lock or signal the event object. This informs the thread it should stop processing and exit gracefully. After signaling the thread in your main program, the only thing left to do is to use the thread.join()
method in main
which will wait for the thread to shut down.
A short example:
import threading
import time
def timed_output(name, delay, run_event):
while run_event.is_set():
time.sleep(delay)
print name,": New Message!"
def main():
run_event = threading.Event()
run_event.set()
d1 = 1
t1 = threading.Thread(target = timed_output, args = ("bob",d1,run_event))
d2 = 2
t2 = threading.Thread(target = timed_output, args = ("paul",d2,run_event))
t1.start()
time.sleep(.5)
t2.start()
try:
while 1:
time.sleep(.1)
except KeyboardInterrupt:
print "attempting to close threads. Max wait =",max(d1,d2)
run_event.clear()
t1.join()
t2.join()
print "threads successfully closed"
if __name__ == '__main__':
main()
If you REALLY need the functionality of killing a thread, use multiprocessing. It allows you to send SIGTERMs to individual "processes" (it's also very similar to the threading module). Generally speaking, threading is for when you are IO-bound, and multiprocessing is for when you are truly processor-bound.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…