条件变量是如何实现的?

发布于 2024-08-22 18:23:36 字数 109 浏览 3 评论 0原文

这让我困惑了很长时间。

给定基本的原子原语,例如比较和比较swap,我可以看到如何实现自旋锁(我可以从中构建互斥体)。

但是,我不知道如何从中构建条件变量。这是怎么做到的?

This has baffled me for a long time.

Given basic atomic primitives like compare & swap, I can see how to implement a spin lock (from which I can build mutexes).

However, I don't see how I can build condition variables out of this. How is this done?

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

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

发布评论

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

评论(1

抹茶夏天i‖ 2024-08-29 18:23:36

这并不是特别简单。以下是 Douglas Schmidt(他主要负责 ACE 库)撰写的一篇论文的链接,该论文详细介绍了使用 Win32(Vista 之前)中可用的同步原语在 Windows 上实现条件变量的几种方法。这些方法包括仅使用基本的、通常在任何操作系统原语上可用的方法,并讨论这些方法的各种限制:

底线(结束语):

本文说明了为什么在 Win32 平台上开发条件变量很棘手且容易出错。开发人员必须解决一些微妙的设计因素。一般来说,我们研究过的不同实现在正确性、效率、公平性和可移植性方面各不相同。没有一种解决方案能以最佳方式提供所有这些品质。

如果公平性至关重要,第 3.4 节中的 SignalObjectsAndWait 解决方案是一个很好的方法。然而,这种方法不如其他解决方案有效,也不那么便携。因此,如果效率或可移植性比公平更重要,则 3.2 节中描述的 SetEvent 方法可能更合适。当然,最简单的解决方案是 Microsoft 在 Win32 API 中简单地提供条件变量。

请注意,从 Vista 开始,Windows 支持使用本机 API 的条件变量:

It's not particularly simple. The following is a link to a paper by Douglas Schmidt (who is also largely responsible for the ACE libraries) that details several approaches for implementing condition variables on Windows using the synchronization primitives available in Win32 (pre-Vista). The approaches include using only the basic, generally available on any OS primitives, and discusses the various limitations of the approaches:

The bottom line (concluding remarks):

This article illustrates why developing condition variables on Win32 platforms is tricky and error-prone. There are several subtle design forces that must be addressed by developers. In general, the different implementations we've examined vary according to their correctness, efficiency, fairness, and portability. No one solution provides all these qualities optimally.

The SignalObjectsAndWait solution in Section 3.4 is a good approach if fairness is paramount. However, this approach is not as efficient as other solutions, nor is it as portable. Therefore, if efficiency or portability are more important than fairness, the SetEvent approach described in Section 3.2 may be more suitable. Naturally, the easiest solution would be for Microsoft to simply provide condition variables in the Win32 API.

Note that starting in Vista, Windows supports condition variables using native APIs:

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