c++ - 在多个自动重置事件上使用 WaitForMultipleObjects

标签 c++ windows multithreading winapi

在我的一个项目中,我创建了多个自动重置事件和两个线程,线程使用WaitForMultipleObjects 在继续运行之前等待一些事件,例如:

HANDLE  hTerminateEvent = CreateEvent(...); // auto reset
HANDLE  hStateChangedEvent = CreateEvent(...); // auto reset

void thread1Func()
{
    HANDLE  handles[2] = { hTerminateEvent, hStateChangedEvent };
    WaitForMultipleObjects(2, handles, FALSE/*bWaitAll*/, INFINITE);
    ...
}

void thread2Func()
{
    HANDLE  handles[2] = { hTerminateEvent, hStateChangedEvent };
    WaitForMultipleObjects(2, handles, FALSE/*bWaitAll*/, INFINITE);
    ...
}

我以前认为一旦hTerminateEvent被单选,两个线程都会被唤醒,但是对于自动重置事件似乎不是这样,哪个被唤醒是随机的,一个被唤醒后, 它将 hTerminateEvent 重置为未发出信号。

我的问题是如何解决这个问题:通过使用手动重置事件?或者是否存在任何设计来解决这个问题?谢谢!

最佳答案

如果您希望两个线程都对hTerminateEvent 使用react,则必须将其设置为手动重置。大概您将它用作告诉多个线程自行终止的信号,因此无论如何将其设置为自动重置是没有意义的。与 hStateChangedEvent 相同。

如果您阅读 CreateEvent()文档,它说:

bManualReset [in]

If this parameter is TRUE, the function creates a manual-reset event object, which requires the use of the ResetEvent function to set the event state to nonsignaled. If this parameter is FALSE, the function creates an auto-reset event object, and system automatically resets the event state to nonsignaled after a single waiting thread has been released.

...

When the state of a manual-reset event object is signaled, it remains signaled until it is explicitly reset to nonsignaled by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object, can be released while the object's state is signaled.

When the state of an auto-reset event object is signaled, it remains signaled until a single waiting thread is released; the system then automatically resets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.

因此当使用自动重置事件时,您无法唤醒同时等待它的多个线程。

关于c++ - 在多个自动重置事件上使用 WaitForMultipleObjects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13831855/

相关文章:

windows - 从 node.js 启动一个外部应用程序

java - += 运算符在 Java 中是线程安全的吗?

multithreading - 我可以从 servlet 生成一个线程吗?

c++ - Boost 几何交集无法正确输出

c++ - std::bind 与 lambda 的效率

c++ - 类的重新定义

c++ - 从辅助线程调用 UpdateWindow()

c++ - pthread_mutex_lock 上的核心转储

windows - 无法删除 Windows 上包含 .git 的文件夹

java - Tomcat java.lang.OutOfMemoryError : GC overhead limit exceeded 错误