如何控制哪个等待线程获得下一个锁?

发布于 2024-11-28 15:54:11 字数 134 浏览 2 评论 0原文

在标准 C# 同步类(如 Monitor)中,如果多个线程等待某个对象解锁,则没有人可以预测哪个线程将获得下一个锁。

我想为所有等待线程分配优先级,因此它们根据此优先级获得锁(如果有多个线程等待解锁)。

我怎样才能实现它?

In standard C# synchronization classes (like Monitor), if several threads wait on some object to be unlocked, no one can predict which thread will get the next lock.

I want to assign priority to all waiting threads, so they get locks according to this priority (if several threads wait for unlock).

How can I implement that?

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

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

发布评论

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

评论(1

浮云落日 2024-12-05 15:54:11

如果没有太多优先级,最简单的方法是为每个级别添加一个主锁和一个 Int32,最高级别除外,指示有多少更高优先级的任务正在等待。想要获取锁的任务将互锁。为每个较低优先级递增计数器,然后等待主锁并检查是否有任何较高优先级的任务正在等待。如果是这样,它将释放并重新获取主锁。否则,Interlocked。递减较低优先级任务的计数器,使用资源,并释放主锁。如果例程放弃获取锁,它应该减少低优先级任务的计数器。

这种方法会因低优先级任务获取和释放主锁而产生一些额外的开销,而高优先级任务需要它,但它应该不会太糟糕。此外,在较高优先级任务完成后较低优先级任务获取锁的顺序实际上可以是随机的。通过为每个优先级添加一个锁,并让每个任务在 Interlocked.Increment 操作之后获取其级别的锁,可以避免此类问题;和以前一样,当锁获取资源或放弃等待资源时,应该发生递减。

The simplest approach, if there aren't too many priority levels, would be to have a main lock plus an Int32 for each level except the highest indicating how many tasks of higher priority are waiting. A task that wants to acquire the lock would Interlocked.Increment the counter for each lower priority, then wait on the main lock and check to see whether any higher-priority tasks were waiting. If so, it would release and reacquire the main lock. Otherwise, Interlocked.Decrement the counters of lower-priority tasks, use the resource, and release the main lock. If the routine gives up on acquiring the lock, it should decrement the counters of lower-priority tasks.

This approach would have some extra overhead from lower-priority tasks acquiring and releasing the master lock while higher-priority tasks wanted it, but it shouldn't be too bad. Further, the order in which lower-priority tasks acquire a lock after a higher-priority task is done with it could be effectively random. Such issues could be avoided by adding a lock for each priority level, and having each task acquire the lock for its level after the Interlocked.Increment operations; as before, the Decrement should happen when the lock either acquires the resource or gives up on waiting for it.

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