Python threading.Event() - Ensuring all waiting threads wake up on event.set()

后端 未结 4 807
有刺的猬
有刺的猬 2021-02-05 19:20

I have a number of threads which wait on an event, perform some action, then wait on the event again. Another thread will trigger the event when it\'s appropriate.

I can

4条回答
  •  情书的邮戳
    2021-02-05 20:08

    If you want discrete, atomic events that can be processed sequentially by each thread, then do as krs1 & bot403 suggested and use a queue. The Python Queue class is synchronized - you do not have to worry about locking to use it.

    If however your needs are simpler (the event tells you that you have data available to read, etc), you can subscribe/register your threads as observers of an object responsible for triggering the events. This object would maintain the list of observer threading.Event objects. On a trigger, it can then call set() on all of the threading.Event objects in the list.

提交回复
热议问题