gpt4 book ai didi

c++ - 如何克服 WaitForMultipleObjects 的 MAXIMUM_WAIT_OBJECTS 限制?

转载 作者:行者123 更新时间:2023-11-30 01:57:13 25 4
gpt4 key购买 nike

由于 WaitForMultipleObjects 函数的 MAXIMUM_WAIT_OBJECTS 限制,我尝试编写自己的“等待线程”函数,但没有成功。你能给我一个提示,怎么做吗?

这是我的“等待线程”函数:

void WaitForThreads(std::set<HANDLE>& handles)
{
for (int i = 0; i < SECONDSTOWAIT; i++)
{
// erase idiom
for (std::set<HANDLE>::iterator it = handles.begin();
it != handles.end();)
{
if (WaitForSingleObject(*it, 0) == WAIT_OBJECT_0)
handles.erase(it++);
else
++it;
}
if (!handles.size())
// all threads terminated
return;
Sleep(1000);
}
// handles.size() threads still running
handles.clear();
}

只要线程运行 WaitForSingleObject 就会返回 WAIT_TIMEOUT 但是当线程终止时返回值是 WAIT_FAILED 而不是 WAIT_OBJECT_0。我猜线程句柄不再有效,因为 GetLastError 返回 ERROR_INVALID_HANDLE

MSDN 建议采用以下解决方案:

  • Create a thread to wait on MAXIMUM_WAIT_OBJECTS handles, then wait on that thread plus the other handles. Use this technique to break the handles into groups of MAXIMUM_WAIT_OBJECTS.
  • Call RegisterWaitForSingleObject to wait on each handle. A wait thread from the thread pool waits on MAXIMUM_WAIT_OBJECTS registered objects and assigns a worker thread after the object is signaled or the time-out interval expires.

但在我看来,两者都太过努力了。

编辑:线程是使用 MFC 函数 AfxBeginThread 创建的。返回的 CWinThread 指针仅用于获取关联的句柄。

CWinThread* thread = AfxBeginThread(LANAbfrage, par);
if ((*thread).m_hThread)
{
threads.insert((*thread).m_hThread);
helper::setStatus("%u LAN Threads active", threads.size());
}
else
theVar->TraceN("Error: Can not create thread");

最佳答案

But it seems to me that both are too much effort.

如果您希望它与等待句柄一起工作,这就是您必须要做的。但是如果你需要的只是在所有线程完成之前阻塞的东西,你可以使用 Semaphore或者可能是 Synchronization Barrier .

关于c++ - 如何克服 WaitForMultipleObjects 的 MAXIMUM_WAIT_OBJECTS 限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18969234/

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