我有一个来自sched模块的 python 计划,我想在一个单独的线程中执行,同时能够随时停止它。我看了看,threading module但不知道哪种方法是实现这一点的最佳方法。时间表示例:>>> s.run()onetwothreeend线程中的调度示例:>>> t = threading.Thread(target = s.run)>>> t.start()onetwo>>> print("ok")okthreeend>>>想要的结果:>>> u = stoppable_schedule(s.run)>>> u.start()>>>onetwo>>> u.stop()"schedule stopped"
1 回答

DIEA
TA贡献1820条经验 获得超2个赞
您所描述的是可以异步停止的线程。
如上所述这里,有两种主要的方法。其中之一是让线程代码检查u.stop()它所做的每个操作的某个事件(在您的示例中由触发)。
另一种解决方案是强制在某个线程中引发错误。这种方法实现起来更简单,但可能会导致意外行为,并且您的线程代码越复杂,它就越危险。
import ctypes
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
tid要终止的线程在哪里。您可以通过运行(在线程中)来获取线程 ID:
print self._thread_id
Tomer Filiba的thread2博客文章中有关于此的更多信息。
添加回答
举报
0/150
提交
取消