2017-09-16 80 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