如何在python中按Ctrl-C时停止线程?

时间:2015-09-06 10:24:26

标签: python multithreading exit-code

我想在接受Ctrl-C时停止线程,所以根据一些文档,我试过:

try:
    threads = [t.join(10) for t in threads if t is not None and t.isAlive()]
except KeyboardInterrupt:
    print "Ctrl-c received! Sending kill to threads..."
    for t in threads:
        t.kill_receives = True

    # some other process

但我发现这也意味着threads will stop after 10 seconds,这不符合我的要求。所以我从代码中删除了10

try:
    threads = [t.join() for t in threads if t is not None and t.isAlive()]
except KeyboardInterrupt:
    print "Ctrl-c received! Sending kill to threads..."
    for t in threads:
        t.kill_receives = True

    # some other process

然后我不能用Ctrl-C杀死程序。

那么我怎样才能杀死优雅的所有线程?

0 个答案:

没有答案