[英]python stoppable sched in separate thread
我有一个来自sched
模块的python计划,我想在一个单独的线程中执行,同时可以随时停止它。 我查看了threading module
但不知道哪种是实现此目的的最佳方法。
时间表示例:
>>> s.run()
one
two
three
end
线程中的时间表示例:
>>> t = threading.Thread(target = s.run)
>>> t.start()
one
two
>>> print("ok")
ok
three
end
>>>
想要的结果:
>>> u = stoppable_schedule(s.run)
>>> u.start()
>>>
one
two
>>> u.stop()
"schedule stopped"
您所描述的是可以异步停止的线程。
如上所述这里 ,有两种主要的方法。 其中之一是让线程代码检查其执行的每个操作是否有某个事件(在示例中由u.stop()
触发u.stop()
。
另一种解决方案是强制在某个线程中引发错误。 这种方法更易于实现,但可能导致意外行为,并且线程代码越复杂,它越危险。
import ctypes
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
tid
是要终止的线程。 您可以通过运行(在线程中)获取线程ID:
print self._thread_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.