51docs/it/python/python-thread-exit.org at master · wuyao721/51docs · GitHub
Skip to content

Latest commit

 

History

History
49 lines (43 loc) · 1.33 KB

python-thread-exit.org

File metadata and controls

49 lines (43 loc) · 1.33 KB

python如何优雅的退出线程和进程

../images/python-thread-exit.png

  1. signal中断主线程
  2. threading.Event中断其它线程

代码如下:

import signal,threading,time

def cleartaskloop(event):
    while not event.isSet():
        event.wait(60)

def friendtaskloop(event):
    while not event.isSet():
        event.wait(1)

if __name__ == '__main__':
    threads = [1,2]
    event = threading.Event()
    threads[0] = threading.Thread(target=friendtaskloop, args=(event,))
    threads[0].start()
    threads[1] = threading.Thread(target=cleartaskloop, args=(event,))
    threads[1].start()
    signal.signal(signal.SIGINT,lambda *args: event.set())
    signal.signal(signal.SIGTERM,lambda *args: event.set())
    while not event.isSet():
        time.sleep(60)
    for t in threads:
        t.join()

转载请注明出处:http://www.wuyao721.com/python-thread-exit.html

#+../images/python-thread-exit.png http://www.wuyao721.com/wp-content/uploads/2013/04/wpid-python-thread-exit.png