关于python中中断一个线程的问题

关于python中中断一个线程的问题

由于一些任务是长时间任务,并不是循环调度的任务,所以设置一个Flag用于判断是否退出线程,虽然安全但是不太方便。
在Thread的_stop()方法的说明是这样的:
···
#After calling ._stop(), .is_alive() returns False and .join() returns
# immediately. ._tstate_lock must be released before calling ._stop().
#
# Normal case: C code at the end of the thread’s life
# (release_sentinel in _threadmodule.c) releases ._tstate_lock, and
# that’s detected by our ._wait_for_tstate_lock(), called by .join()
# and .is_alive(). Any number of threads may call ._stop()
# simultaneously (for example, if multiple threads are blocked in
# .join() calls), and they’re not serialized. That’s harmless -
# they’ll just make redundant rebindings of ._is_stopped and
# ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the
# “assert self._is_stopped” in ._wait_for_tstate_lock() always works
# (the assert is executed only if ._tstate_lock is None).
#
# Special case: _main_thread releases ._tstate_lock via this
# module’s _shutdown() function.
···
如果需要在一个长时间线程任务中进行强制中断可以考虑如下的方法(可能存在一些问题,不建议强制退出)以下是在python3.10.7中的测试结果

import threading
import time
def my_thread_func():
    try:
        while True:
            time.sleep(3)
            print(my_thread._tstate_lock)

    except KeyboardInterrupt:
        pass

my_thread = threading.Thread(target=my_thread_func)
my_thread.start()


# 在主线程中中断当前线程
time.sleep(6)
# special case: _main_thread 直接释放_tstate_lock
my_thread._tstate_lock.release()
print(f"线程alive:{my_thread.is_alive()}")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值