from twisted.internet import reactor from twisted.internet import threads from twisted.internet import defer import time def worker(arg): print 'Hello world' time.sleep(10) return 1 def run(): print 'Starting workers' l = [] for x in range(2): l.append(threads.deferToThread(worker,x)) return defer.DeferredList(l) def res(results): print results reactor.stop() d = run() d.addCallback(res) reactor.run()
如何通过超时停止工人?
解决方法
除非与您合作,否则不能中断线程. time.sleep(10)不合作,所以我认为你不能打断这个工人.如果您有另一种具有多个离散阶段的工作者,或者在某些任务的循环中操作,那么您可以执行以下操作:
def worker(stop,jobs): for j in jobs: if stop: break j.do() stop = [] d = deferToThread(worker) # This will make the list eval to true and break out of the loop. stop.append(None)
这也不是Twisted特定的.这就是线程在Python中的工作方式.