簡體   English   中英

time.sleep阻塞線程中的循環

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM