2016-11-15 57 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