当前位置: 代码网 > it编程>前端脚本>Python > python中停止线程的方法代码举例

python中停止线程的方法代码举例

2024年06月13日 Python 我要评论
1 threading.event()方法一种常见的方法是使用标志位来通知线程应该停止。线程可以定期检查这个标志位,如果它被设置为停止,那么线程就结束其执行。下面是一个简单的例子:import thr

1 threading.event()方法

  • 一种常见的方法是使用标志位来通知线程应该停止。线程可以定期检查这个标志位,如果它被设置为停止,那么线程就结束其执行。下面是一个简单的例子:
import threading  
import time  
  
class mythread(threading.thread):  
    def __init__(self):  
        super(mythread, self).__init__()  
        self.stop_event = threading.event()  
  
    def run(self):  
    	# 清空设置
        self.stop_event.clear()
        while not self.stop_event.is_set():  
            print("thread is running...")  
            time.sleep(1)  
  
    def stop(self):  
        self.stop_event.set()  
  
# 创建线程  
thread = mythread()  
thread.start()  
  
# 在某个时间点,停止线程  
time.sleep(5)  
thread.stop()
  • 需要注意的是,这只是一种优雅的停止线程的方法,它依赖于线程在run方法中定期检查stop_event。如果线程没有这样的检查,或者它正在执行一个无法被中断的阻塞操作(例如io操作),那么这种方法可能无法立即停止线程。

2 子线程抛出异常,立刻停止

  • python中,使用ctypespythreadstate_setasyncexc函数来在子线程中异步抛出一个异常是一种相对底层的做法,它可以直接在子线程的上下文中触发一个异常。然而,这种做法需要谨慎使用,因为它可能会导致线程状态不稳定或未定义的行为,特别是如果线程没有正确地处理异常。
import threading
import time
import ctypes
import inspect

def do_some_task():
    while true:
        time.sleep(1)
        print("子线程!1")
        time.sleep(1)
        print("子线程!2")
        time.sleep(1)
        print("子线程!3")
        time.sleep(1)
        print("子线程!4")
        time.sleep(1)
        print("子线程!5")

def async_raise(thread_id, exctype):
    """
    通过c语言的库抛出异常
    :param thread_id:
    :param exctype:
    :return:
    """
    # 在子线程内部抛出一个异常结束线程
    thread_id = ctypes.c_long(thread_id)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.pythreadstate_setasyncexc(thread_id, ctypes.py_object(exctype))
    if res == 0:
        raise valueerror("线程id违法")
    elif res != 1:
        ctypes.pythonapi.pythreadstate_setasyncexc(thread_id, none)
        raise systemerror("异常抛出失败")

def stop_thread_now(thread):
    # 结束线程
    async_raise(thread.ident, systemexit)

if __name__ == "__main__":
    # 可以在子线程任何时候随时结束子线程
    sub_thread = threading.thread(target=do_some_task,name="sub_thread")
    sub_thread.start()
    print(sub_thread.is_alive())
    time.sleep(7)
    stop_thread_now(sub_thread)
    time.sleep(1)
    print(sub_thread.is_alive())

附:线程停止的最佳实践

在实际的应用中,我们应该遵循以下最佳实践来停止线程:

  • 使用标志位或event对象来控制线程的停止,这样可以在线程执行的关键点进行安全的停止。
  • 在线程的代码中定期检查标志位或event对象的状态,并根据状态决定是否退出循环。
  • 在主线程中修改标志位或event对象的状态时,需要使用线程锁来保证线程安全性。
  • 避免使用thread的stop()方法来终止线程的执行。

总结 

到此这篇关于python中停止线程方法的文章就介绍到这了,更多相关python停止线程方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com