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

后端 未结 4 812
有刺的猬
有刺的猬 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:21

    You don't need an Event, and you don't need both a Lock and a Queue. All you need is a Queue.

    Call queue.put to drop a message in without waiting for it to be delivered or processed.

    Call queue.get in the worker thread to wait for a message to arrive.

    import threading
    import Queue
    
    active_queues = []
    
    class Worker(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.mailbox = Queue.Queue()
            active_queues.append(self.mailbox)
    
        def run(self):
            while True:
                data = self.mailbox.get()
                if data == 'shutdown':
                    print self, 'shutting down'
                    return
                print self, 'received a message:', data
    
        def stop(self):
            active_queues.remove(self.mailbox)
            self.mailbox.put("shutdown")
            self.join()
    
    
    def broadcast_event(data):
        for q in active_queues:
            q.put(data)
    
    t1 = Worker()
    t2 = Worker()
    t1.start()
    t2.start()
    broadcast_event("first event")
    broadcast_event("second event")
    broadcast_event("shutdown")
    
    t1.stop()
    t2.stop()
    

    The messages don't have to be strings; they can be any Python object.

提交回复
热议问题