gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:20:24 29 4
gpt4 key购买 nike

在我的一个项目中,我创建了多个自动重置事件和两个线程,线程使用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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com