问题
I am writing a Multithreaded Python application, in which each thread should wake up under the following circumstances:
- A signal from a main thread
- A Timer call started by itself
In other words, threads should wake up according to a timer they set for themselves, and be able to respond to a signal from a managing thread whenever a relevant event appears.
What's the idiomatic way to implement a dual (Timer/Event) wake-up mechanism?
回答1:
Well, threading.Event, has a wait method, which takes a timeout. So you could do something as simple as
In main thread:
sleepEvent = threading.Event()
pass that to your other threads, and in them:
sleepEvent.wait(10) # wait for up to 10 seconds
Now your thread will either wait 10 seconds (like a timer) or will clear the wait if the main thread calls
sleepEvent.set()
来源:https://stackoverflow.com/questions/27463626/make-a-thread-wait-for-either-a-timer-or-a-signal