2017-09-16 78 views
1

當我在線程中運行While True循環並使用time.sleep()函數時,循環停止循環。time.sleep塊while循環線程

我使用代碼:

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() 
+0

你所說的「停止循環」意思? – roganjosh

+0

它只是掛起。它不是印刷'循環'或者做任何事情。 – MrPete

+2

該代碼應該是一個完整的例子嗎? 'time.sleep'行會給出一個'NameError'。而且,一旦線程啓動,腳本將立即退出。 – ekhumoro

回答

2

你進口sleep作爲

from time import sleep

所以你要調用sleep在run()sleep(0.5)或你必須改變進口爲

import time 我不推薦。

+1

爲什麼不建議使用'import time'? – RedEyed

+1

兩個人都有自己的優點和缺點。如果您只需要使用一件物品,假設OP只是展示循環特性,則不需要導入整個包裝。除非你需要從時間導入大量項目或者說module_x,我沒有看到這麼做的原因。同樣經常輸入'module.item'可能真是一團糟。 :) –

+0

好吧,我的錯。有問題的問題.. thx。 – MrPete

3

循環停止,因爲您將線程標記爲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