所以…我想可能是通过将10个不同的SO帖子以一种我在任何一个SO帖子上都没有看到的方式组合在一起来解决的…请批评并告诉我这是愚蠢还是出色… ?
[因为这个问题与至少两个其他问题紧密相关…我在两个相关线程中将我提出的解决方案作为独立答案发布:1 2]
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]
我认为这就是适用于我的应用程序的秘密调味料.经过一段固定时间后,现在我的子线程已正确清理,没有循环标记检查该子线程中的废话……而且我什至在子线程中甚至得到了一丝微弱的控制权,可以在其中执行一些最终状态检查和清理.