介绍
小编给大家分享一下怎么让python线程强制停止工作,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!
线程模块没有停止方法,是为了安全,但是我们需要停止子线程呢。小编罗列了,可以有几种安全停止线程的方式,主要涉及的是需要将共享变量作为标志,事件对象还有调用C函数接口,但是如果碰到需要去强制停止线程的方式,这就需要我们去调用C函数接口。
<强>强制停止线程,ctypes调用C函数接口强>
import 线程 import 时间 import 检查 import ctypes def _async_raise (tid, exctype): ,,,if not inspect.isclass (exctype):,, #,检查exctype对象,是不是类。是类返回真,不是类返回错误的 ,,,,,,,exctype =,类型(exctype) ,,,res=ctypes.pythonapi.PyThreadState_SetAsyncExc (tid, ctypes.py_object (exctype)) ,,,if res ==, 0: ,,,,,,,raise ValueError (“invalid thread id") ,,,elif res !=, 1: ,,,,,,,ctypes.pythonapi.PyThreadState_SetAsyncExc (tid,,没有) ,,,,,,,raise SystemError (“PyThreadState_SetAsyncExc failed") def stop_thread(线程): _async_raise (thread.ident, SystemExit),, #, thread.ident 返回线程,id def 工作():,,#,线程函数 ,,,while 正确的: ,,,,,,,印刷(& # 39;工作中& # 39;) ,,,,,,,time . sleep (0.5) ,,,print(& # 39;子线程退出& # 39;) if __name__ ==,“__main__": ,,,t =, threading.Thread(目标=工作) ,,,t.start () ,,,time . sleep (1) ,,,print(“主线程退出“) ,,,stop_thread (t) #,打印返回: “““ 工作中 工作中 工作中主线程退出 “““
以上是“怎么让python线程强制停止工作”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!