龙空技术网

python线程之八:线程停止的3种方式,5个实例

python一看便懂 461

前言:

今天朋友们对“python线程安全”大体比较珍视,朋友们都想要剖析一些“python线程安全”的相关资讯。那么小编也在网络上汇集了一些关于“python线程安全””的相关内容,希望兄弟们能喜欢,看官们一起来了解一下吧!

线程模块没有停止方法,是为了安全,但是我们需要停止子线程呢。

我这里给出四种安全停止线程的方式,加一种网上给出了强制停止线程的方式

安全停止的四种方式是,判断标识,退出线程强制停止线程的方式是,ctypes 调用C语言的内部函数,强制退出线程

我们用主线程停止子线程作为示例,来用代码演示,如下五种方式,建议使用第三、第四种方式

1、示例一:安全停止线程,共享变量作为标志

2、示例二:安全停止线程,共享变量作为标志

3、示例三:安全停止线程,共享变量 Event() 对象

4、示例四:安全停止线程,共享变量 Event() 对象

5、示例五:强制停止线程,ctypes 调用 C 函数接口

import threadingimport timeimport inspectimport ctypesdef _async_raise(tid, exctype):    if not inspect.isclass(exctype):  # 检查exctype对象,是不是类。是类返回True,不是类返回False        exctype = type(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, None)        raise SystemError("PyThreadState_SetAsyncExc failed")def stop_thread(thread):    _async_raise(thread.ident, SystemExit)  # thread.ident 返回线程 iddef work():  # 线程函数    while True:        print('工作中')        time.sleep(0.5)    print('子线程退出')if __name__ == "__main__":    t = threading.Thread(target=work)    t.start()    time.sleep(1)    print("主线程退出")    stop_thread(t)# 打印返回:"""工作中工作中工作中主线程退出"""

标签: #python线程安全