2016-11-15 4 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)を使用してスリープコマンドをスレッドに通知します。 –

+0

@LutzHorn新しいアカウントを作成しましたか? – Maroun

+0

@MarounMaroun? –

答えて

1

1.5秒のためのカウンタを作成し、対抗スリープ機能の増分を行います

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 
関連する問題