Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fair semaphore in python

Is it possible to have a fair semaphore in python, one that guarantees that blocking threads are unblocked in the order they call acquire()?

like image 901
r.v Avatar asked Nov 16 '11 20:11

r.v


1 Answers

You might have to build one from other moving parts. For example, create a Queue.Queue() to which each listener posts a brand-new Event() on which it then waits. When it is time to wake up one of the waiting threads, pop off the item on the queue that has been waiting longest — it will be one of those event objects — and release the thread through event.set().

Obviously, you could also use a semaphore per waiting process, but I like the semantics of an Event since it can clearly only happen once, while a semaphore has the semantics that its value could support many waiting threads.

To set the system up:

import Queue
big_queue = Queue.Queue()

Then, to wait:

import threading
myevent = threading.Event()
big_queue.put(myevent)
myevent.wait()

And to release one of the waiting threads:

event = big_queue.get()
event.set()

I suppose the weakness of this approach is that the thread doing the set/release has to wait for a waiting thread to come along, whereas a true semaphore would let several releases proceed even if no one was waiting yet?

like image 111
Brandon Rhodes Avatar answered Oct 13 '22 23:10

Brandon Rhodes