time.sleep 阻塞线程中的 while 循环

time.sleep blocks while loop in thread

当我在线程中 运行 一个 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)

要启动线程,我正在使用 this 代码:

thread = drive_worker()

您将 sleep 导入为

from time import sleep

所以你必须将 run() 中的睡眠调用为 sleep(0.5) 或者你必须将导入更改为

import time 我不推荐。

循环停止,因为您将线程标记为 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