Python阻塞线程终止方法?

Python blocked thread termination method?

我对 Python 编程有疑问。我正在编写一个有线程的代码。该线程是阻塞线程。阻塞线程的意思是:一个线程正在等待一个事件。如果事件没有设置,这个线程必须等到事件被设置。我期望块线程必须等待事件而没有任何等待超时!
启动阻塞线程后,我编写了一个永远循环来计算计数器。问题是:当我想通过 Ctrl+C 终止我的 Python 程序时,我无法正确终止被阻塞的线程。这个话题还活着!我的代码在这里。

import threading
import time

def wait_for_event(e):
    while True:
        """Wait for the event to be set before doing anything"""
        e.wait()
        e.clear()
        print "In wait_for_event"

e = threading.Event()
t1 = threading.Thread(name='block',
                      target=wait_for_event,
                      args=(e,))
t1.start()

# Check t1 thread is alive or not
print "Before while True. t1 is alive: %s" % t1.is_alive()

counter = 0
while True:
    try:
        time.sleep(1)
        counter = counter + 1
        print "counter: %d " % counter
    except KeyboardInterrupt:
        print "In KeyboardInterrupt branch"
        break

print "Out of while True"
# Check t1 thread is alive
print "After while True. t1 is alive: %s" % t1.is_alive()

输出:

$ python thread_test1.py
Before while True. t1 is alive: True
counter: 1
counter: 2
counter: 3
^CIn KeyboardInterrupt branch
Out of while True
After while True. t1 is alive: True

有人可以帮我吗?我想问2个问题。
1. 是否可以通过Ctrl+C停止被阻塞的线程?如果可以,请给我一个可行的方向。
2.如果我们通过Ctrl+\键盘停止Python程序或者重置运行Python程序的硬件(例如PC),被阻塞的线程是否可以终止?

Ctrl+C 仅停止主线程,您的线程未处于 daemon 模式,这就是它们保持 运行 的原因,这就是保持进程存活。首先让你的线程成为守护进程。

t1 = threading.Thread(name='block',
                      target=wait_for_event,
                      args=(e,))
t1.daemon = True
t1.start()

与您的其他主题类似。但是还有另一个问题——一旦主线程启动了你的线程,它就没有别的事可做了。所以它退出,线程立即被销毁。所以让我们让主线程保持活动状态:

import time
while True:
    time.sleep(1)

请看一下this,希望您能得到其他答案。

如果您需要终止所有 运行ning python 的进程,您可以从命令行简单地 运行 pkill python。 这有点极端,但会奏效。

另一种解决方案是在代码中使用锁定,请参阅 here: