Win32 事件与信号量

发布于 2024-08-31 22:42:36 字数 234 浏览 6 评论 0原文

基本上我需要替换 Condition Variable 和 SleepConditionVariableCS,因为它只支持 Vista 和 UP。 (对于C++)

有人建议使用Semaphore,我也找到了CreateEvent。

基本上,我需要有一个线程等待 WaitForSingleObject,直到一个或多个其他线程告诉我有事情要做。

我应该在什么情况下使用信号量和获胜事件?

谢谢

Basically I need a replacement for Condition Variable and SleepConditionVariableCS because it only support Vista and UP. (For C++)

Some suggested to use Semaphore, I also found CreateEvent.

Basically, I need to have on thread waiting on WaitForSingleObject, until something one or more others thread tell me there is something to do.

In which context should I use a Semaphore vs an Win Event?

Thanks

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

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

发布评论

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

评论(3

慢慢从新开始 2024-09-07 22:42:36

在你的情况下,我会自己使用一个事件。当您希望线程开始运行时,向该事件发出信号。工作完成:)

编辑:信号量和事件之间的区别归结为内部计数。如果有多个ReleaseSemaphore,那么2个WaitForSingleObjects也会被释放。事件本质上是布尔值。如果两个不同的地方同时发出信号事件,那么等待将被释放,并将被设置回未发出信号的状态(取决于您是否有自动或手动重置)。如果您需要同时从多个位置发出信号并且等待线程运行两次,那么此事件行为可能会导致死锁。

In your case I'd use an event myself. Signal the event when you want the thread to get going. Job done :)

Edit: The difference between semaphores and events comes down to the internal count. If there are multiple ReleaseSemaphores then 2 WaitForSingleObjects will also be released. Events are boolean by nature. If 2 different places Signal event simultaneously then the wait will get released and it will get set back to unsignalled (dependent on if you have automatic or manual resetting). If you need it to be signalled from multiple places simultaneously and for the waiting thread to run twice then this event behaviour could lead to a deadlock.

时光倒影 2024-09-07 22:42:36

一般情况下,在 Windows 上替换条件变量极其困难且容易出错。要么:

  1. 使用其他人的实现(例如,Boost.Thread)。
  2. 重新思考您要解决的问题,看看 Win32 是否可以解决。根据您的描述,一个事件可能就足够了,但是如果服务员需要由其他线程将设置的某些条件表达式触发,而不仅仅是信号,那么您最好回到选项 1。

Replacing condition variables on Windows is extremely difficult and error-prone in the general case. Either:

  1. Use someone else's implementation (e.g., Boost.Thread).
  2. Rethink the problem you are trying to solve and see if Win32 can do it. Based on your description, an Event might suffice, but if the waiter needs to be triggered by some conditional expression that the other threads will setup, and not just a signal, you're better off going back to option 1.
星星的軌跡 2024-09-07 22:42:36

Use boost::condition_variable if at all possible. I've been down this road before (see msg on microsoft.public.win32.programmer.kernel) and the Win32 Event API does not suffice; there are problems using events.

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