简体   繁体   English

time.sleep阻塞线程中的循环

[英]time.sleep blocks while loop in thread

When I run a While True loop in thread and use time.sleep() function the loop stops looping. 当我在线程中运行While True循环并使用time.sleep()函数时,循环停止循环。

I am using this code: 我正在使用代码:

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)

To start the thread I am using this code: 要启动该线程,我使用代码:

thread = drive_worker()

The loop stops because you flagged the thread as daemon . 循环停止,因为您将该线程标记为daemon The program terminates when there are only daemon threads left running. 当只有守护程序线程继续运行时,程序终止。

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

Or make the main thread wait for the the daemon thread to finish 或者让主线程等待守护程序线程完成

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

You imported sleep as 你导入sleep

from time import sleep

so you have to call sleep in run() as sleep(0.5) or you have to change import as 所以你必须在run()调用sleep作为sleep(0.5)或者你必须将import更改为

import time which I do not recommend. 我不推荐的import time

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM