主程序完成后守护程序线程无法退出

时间:2017-06-29 18:01:13

标签: python multithreading

我已经提到了这个帖子,但它似乎已经过时了 而且似乎并不是一个干净的解释

Python daemon thread does not exit when parent thread exits

我正在运行python 3.6并尝试从IDLE或Spyder IDE运行脚本。

这是我的代码:

import threading
import time

total = 4

def creates_items():
    global total
    for i in range(10):
        time.sleep(2)
        print('added item')
        total += 1
    print('creation is done')


def creates_items_2():
    global total
    for i in range(7):
        time.sleep(1)
        print('added item')
        total += 1
    print('creation is done')


def limits_items():

    #print('finished sleeping')

    global total
    while True:
        if total > 5:

            print ('overload')
            total -= 3
            print('subtracted 3')
        else:
            time.sleep(1)
            print('waiting')


limitor = threading.Thread(target = limits_items, daemon = True)
creator1 = threading.Thread(target  = creates_items)
creator2 = threading.Thread(target = creates_items_2)


print(limitor.isDaemon())


creator1.start()
creator2.start()
limitor.start()


creator1.join()
creator2.join()

print('our ending value of total is' , total)

尽管是一个守护程序线程,但是限制线程似乎并没有结束。

这是从IDLE还是Spyder开始工作的方法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

我有同样的问题并通过使用多处理而不是线程来解决它:

from multiprocessing import Process
import multiprocessing
from time import sleep

def daemon_thread():
    for _ in range(10):
        sleep(1)
        print("Daemon")

if __name__ == '__main__':
    multiprocessing.freeze_support()
    sub_process = Process(target = daemon_thread, daemon = True)
    sub_process.start()

    print("Exiting Main")

我还没有真正理解为什么我需要调用freeze_support(),但它使代码工作。