简体   繁体   中英

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.

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 . 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

from time import sleep

so you have to call sleep in run() as sleep(0.5) or you have to change import as

import time which I do not recommend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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