Make a thread wait for either a Timer or a Signal?

给你一囗甜甜゛ 提交于 2019-12-11 11:37:40

问题


I am writing a Multithreaded Python application, in which each thread should wake up under the following circumstances:

  1. A signal from a main thread
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!