简体   繁体   English

python 线程:当多个线程之一失败时退出程序

[英]python threading: exit program when one of many threads fail

I would like to find a way to have a script exit when one of the threads fail.当一个线程失败时,我想找到一种方法让脚本退出。 I have experimented with _thread.interrupt_main() and daemon = True as follow:我已经尝试了_thread.interrupt_main()daemon = True如下:

import threading
import time
import _thread


def run1(x):
    while True:
        time.sleep(1)
        print(x)


def run_and_stop(x):
    i = 0
    while True:
        time.sleep(1)
        print(x)
        i += 1
        if i == 5:
            _thread.interrupt_main()


t1 = threading.Thread(target = run1, args = ('a', ), daemon = True)
t2 = threading.Thread(target = run1, args = ('b', ), daemon = True)
t3 = threading.Thread(target = run1, args = ('c', ), daemon = True)
t4 = threading.Thread(target = run_and_stop, args = ('d', ), daemon = True)
t1.start()
t2.start()
t3.start()
t4.start()

time.sleep(100)

Here the program should exit after 5s: the last thread reaches the interrupt_main() command, and since the other threads are daemon, they should all shut down then.这里程序应该在 5s 后退出:最后一个线程到达了interrupt_main()命令,并且由于其他线程是守护进程,所以它们应该都关闭。

However it doesn't happen so.然而事实并非如此。 Can anyone explain me why and provide a solution for the program to exit then?谁能解释我为什么并为程序退出提供解决方案?

On Unix, time.sleep() uses select() .在 Unix 上, time.sleep time.sleep()使用select() We could interrupt it by signaling the process, or explicitly the main thread, via kill() or pthread_kill() .我们可以通过kill()pthread_kill()向进程发出信号或显式地向主线程发出信号来中断它。

As for _thread.interrupt_main , from this discussion :至于_thread.interrupt_main ,来自这个讨论

"Looking at the implementation, _thread.interrupt_main just calls PyErr_SetInterrupt. It doesn't appear to send a signal. I played with “strace” and couldn't see any evidence of a signal. I guess it just sets a flag that will be polled. To actually interrupt the “sleep” call, you might need to use “pthread_kill” or similar (at least on Unix)." “看看实现,_thread.interrupt_main 只是调用 PyErr_SetInterrupt。它似乎没有发送信号。我玩了“strace”,看不到任何信号的证据。我猜它只是设置了一个标志轮询。要真正中断“睡眠”调用,您可能需要使用“pthread_kill”或类似的(至少在 Unix 上)。

def run_and_stop(x):
    i = 0
    while True:
        time.sleep(1)
        print(x)
        i += 1
        if i == 5:
            os.kill(os.getpid(), signal.SIGINT)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM