Fair semaphore in python

好久不见. 提交于 2019-12-10 13:24:37

问题


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


回答1:


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?




回答2:


With Brandon having addressed the "fair semaphore" question, it might be useful to look at a related problem of barriers, a waiting point for threads to reach and then be released at the same time: http://docs.python.org/py3k/whatsnew/3.2.html#threading



来源:https://stackoverflow.com/questions/8158442/fair-semaphore-in-python

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