python中的公平信号量 [英] Fair semaphore in python

查看:33
本文介绍了python中的公平信号量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中是否有可能有一个公平的信号量,一个保证阻塞线程按照它们调用 acquire() 的顺序解除阻塞?

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

推荐答案

您可能需要从其他活动部件构建一个.例如,创建一个 Queue.Queue(),每个侦听器向其发送一个全新的 Event(),然后等待.当需要唤醒一个等待的线程时,弹出队列中等待时间最长的项目——它将是那些事件对象之一——并通过 event.set().

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().

显然,您也可以为每个等待进程使用一个信号量,但我喜欢 Event 的语义,因为它显然只能发生一次,而信号量的语义是它的值可以支持许多等待线程.

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.

设置系统:

import Queue
big_queue = Queue.Queue()

然后,等待:

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()

我认为这种方法的弱点是执行 set/release 的线程必须等待一个等待的线程出现,而真正的信号量会让几个释放继续进行,即使没有人在等待?

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?

这篇关于python中的公平信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆