温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么让python线程强制停止工作

发布时间:2020-12-14 09:20:26 来源:亿速云 阅读:641 作者:小新 栏目:编程语言

小编给大家分享一下怎么让python线程强制停止工作,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

线程模块没有停止方法,是为了安全,但是我们需要停止子线程呢。小编罗列了,可以有几种安全停止线程的方式,主要涉及的是需要将共享变量作为标志、event对象还有调用C函数接口,但是如果碰到需要去强制停止线程的方式,这就需要我们去调用C函数接口。

强制停止线程,ctypes 调用 C 函数接口

import threading
import time
import inspect
import ctypes
def _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 返回线程 id
def 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线程强制停止工作”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI