Equivalent of thread.interrupt_main() in Python 3

前提是你 提交于 2019-12-12 21:34:28

问题


In Python 2 there is a function thread.interrupt_main(), which raises a KeyboardInterrupt exception in the main thread when called from a subthread.

This is also available through _thread.interrupt_main() in Python 3, but it's a low-level "support module", mostly for use within other standard modules.

What is the modern way of doing this in Python 3, presumably through the threading module, if there is one?


回答1:


Well raising an exception manually is kinda low-level, so if you think you have to do that just use _thread.interrupt_main() since that's the equivalent you asked for (threading module itself doesn't provide this).

It could be that there is a more elegant way to achieve your ultimate goal, though. Maybe setting and checking a flag would be already enough or using a threading.Event like @RFmyD already suggested, or using message passing over a queue.Queue. It depends on your specific setup.




回答2:


You might want to look into the threading.Event module.



来源:https://stackoverflow.com/questions/53064280/equivalent-of-thread-interrupt-main-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!