关于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()}")