Python阻塞线程终止方法?

时间:2017-08-31 12:23:34

标签: python multithreading pthreads signals python-multithreading

我在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

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

2 个答案:

答案 0 :(得分:2)

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,我希望您能得到其他答案。

答案 1 :(得分:1)

如果你需要杀死所有正在运行的python进程,你可以从命令行运行pkill python。 这有点极端,但可行。

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