如何使用V唤醒指定的P?

发布于 2024-10-04 07:49:45 字数 133 浏览 1 评论 0原文

假设我们有一个信号量 s,并且有多个线程通过调用 P(s) 来等待它。然后 V(s) 会唤醒其中的一个线程。有没有办法唤醒指定的线程而不是让系统来做决定?例如,在理发店问题中,每次理发后,理发师都希望为等待时间最长的顾客提供服务,而不是随机为顾客服务。

Suppose we have a semaphore s and there are multiple threads waiting for it by calling P(s). Then V(s) would wake up exact one thread among them. Is there a way to wake up a designated thread instead of having the system make the decision? For instance, in the barbershop problem, after each haircut, the barber wants to serve the longest waiting customer, instead of a random one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

九厘米的零° 2024-10-11 07:49:45

您可以只使用队列来存储 P。这会让你根据最长的等待时间来完成它。如果没有,您可以根据您想要的任何参数存储在排序树中,并在需要时删除。

我认为关键在于 P 的某种排序机制,这不会太复杂。

You could just use a queue to store the P's. that'll let you do it based off of longest wait. If not you could store in a sorted tree based off of whatever paramater you want, and remove when needed.

I think the crux of it would be some sort of ordering mechanism for the P's, which souldn't be too complicated.

愿得七秒忆 2024-10-11 07:49:45

这取决于信号量的实现。您必须使用智能信号量来创建等待线程队列并以正确的顺序向它们发出信号。我认为 Windows 上的常规信号量实现不是这样工作的。它只是向操作系统发送一个信号,操作系统又向任何等待的线程发送一个信号。如果使用 lifo 堆栈甚至更有意义,因为这更容易实现。
但是通过实现队列(可以是链表或循环数组)来自己构建它并不困难。

It depends on the implementation of the semaphore. You would have to use a smart semaphore that creates a queue of waiting threads and signals them in the right order. I think the regular semaphore implementation on Windows doesn't work that way. It just sends a signal to the OS, which in turn sends a signal to any of the waiting threads. It would even make sense if this uses a lifo stack, because that is implemented more easily.
But it wouldn't be hard to build this yourself by implementing a queue, which could be a linked list, or a cyclic array.

帅气称霸 2024-10-11 07:49:45

不,不是经典信号量本身。如果您想要类似队列的行为,您可以创建一个队列(带有一个信号量,或者可能有几个)来保护队列的共享数据结构。

现实情况是,虽然理论上信号量是进行同步所需的全部,但您很少(永远不会?)编写大量直接使用裸信号量的实际代码。大多数时候,您使用(例如)信号量构建更高级别的构造来保护该构造中的关键数据。

No, not with classical semaphores by themselves. If you want queue-like behavior, you create a queue (with a semaphore, or maybe a couple of them) to protect the queue's shared data structure(s).

The reality is, that while semaphores are theoretically all you need to do synchronization, you'd rarely (never?) write a significant body of real code that just used bare semaphores directly. Most of the time, you build higher-level constructs with (for example) a semaphore to protect that critical data in that construct.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文