[英]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)
要启动该线程,我使用此代码:
thread = drive_worker()
循环停止,因为您将该线程标记为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
你导入sleep
为
from time import sleep
所以你必须在run()
调用sleep作为sleep(0.5)
或者你必须将import更改为
我不推荐的import time
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.