私信  •  关注

slumtrimpet

slumtrimpet 最近创建的主题
slumtrimpet 最近回复了
7 年前
回复了 slumtrimpet 创建的主题 » 强制退出运行python中的线程[duplicate]

我来晚了,但我一直在努力 a similar question 下面的代码似乎可以很好地解决这个问题,并让我在守护子线程退出时执行一些基本的线程状态检查和清理:

import threading
import time
import atexit

def do_work():

  i = 0
  @atexit.register
  def goodbye():
    print ("'CLEANLY' kill sub-thread with value: %s [THREAD: %s]" %
           (i, threading.currentThread().ident))

  while True:
    print i
    i += 1
    time.sleep(1)

t = threading.Thread(target=do_work)
t.daemon = True
t.start()

def after_timeout():
  print "KILL MAIN THREAD: %s" % threading.currentThread().ident
  raise SystemExit

threading.Timer(2, after_timeout).start()

产量:

0
1
KILL MAIN THREAD: 140013208254208
'CLEANLY' kill sub-thread with value: 2 [THREAD: 140013674317568]