2016-11-15 23 views
0
import time 
import threading 


def do_something(): 
    while True: 
     time.sleep(0.5) 
     print('I am alive') 


def main(): 
    while True: 
     time.sleep(1) 
     print('Hello') 


daemon_thread = threading.Thread(target=do_something, daemon=True) 
daemon_thread.start() 
main() 

有没有一种方法可以让daemon_threaddo_something()以外睡3秒钟?我的意思是假设像daemon_thread.sleep(3)有没有一种方法可以将线程从线程之外置入睡眠状态?

+0

你可以使用['queue'](https://docs.python.org/3/library/ queue.html)将睡眠命令传递给线程。 – 2016-11-15 07:43:05

+0

@LutzHorn你创建了一个新帐户吗? – Maroun

+0

@MarounMaroun? – 2016-11-15 07:47:15

回答

1

创建半秒计数器,然后进行睡眠功能增量该计数器:

lock = Lock() 
counter = 0 


def do_something(): 
    global counter 
    while True: 
     time.sleep(0.5) 
     with lock: 
      if counter == 0: 
       print('I am alive') 
      else: 
       counter -= 1 


def increment(seconds): 
    global counter 
    with lock: 
     counter += 2*seconds 


# after starting thread 

increment(3) # make the thread wait three seconds before continuing 
相关问题