time.sleep阻塞线程中的循环

时间:2017-09-16 16:30:23

标签: python multithreading loops python-multithreading

当我在线程中运行While True循环并使用time.sleep()函数时,循环停止循环。

我正在使用代码:

import threading
from time import sleep

class drive_worker(threading.Thread):

    def __init__(self):
        super(drive_worker, self).__init__()
        self.daemon = True
        self.start()

    def run(self):
        while True:
            print('loop')
            #some code
            time.sleep(0.5)

要启动该主题,我正在使用代码:

thread = drive_worker()

2 个答案:

答案 0 :(得分:2)

循环停止是因为您将线程标记为daemon。 当只剩下守护程序线程时,程序终止。

self.daemon = True # remove this statement and the code should work as expected

或者让主线程等待守护程序线程完成

dthread = drive_worker()
# no call to start method since your constructor does that
dthread.join() #now the main thread waits for the new thread to finish

答案 1 :(得分:1)

您导入sleep

from time import sleep

因此您必须将run()中的睡眠称为sleep(0.5),否则您必须将导入更改为

import time 我不推荐。

相关问题