gpt4 book ai didi

c++ - 带有 CWinThread 指针数组的 WaitForMultipleObjects

转载 作者:太空宇宙 更新时间:2023-11-04 16:25:51 33 4
gpt4 key购买 nike

我有一个通过 AfxBeginThread 生成线程的循环,它将 CWinThread 指针存储在一个数组中。在每次迭代中,我检查线程是否为空并将线程的句柄存储在另一个数组中。

const unsigned int maxThreads = 2;
CWinThread* threads[maxThreads];
HANDLE* handles[maxThreads];
for(unsigned int threadId=0; threadId < maxThreads; ++threadId)
{
threads[threadId] = AfxBeginThread(endToEndProc, &threadId,
0,0,CREATE_SUSPENDED);
if(threads[threadId] == NULL)
{
// die carefully
}
threads[threadId]->m_bAutoDelete = FALSE;
handles[threadId] = &threads[threadId]->m_hThread;
::ResumeThread(handles[threadId]);
}

DWORD result = ::WaitForMultipleObjects(maxThreads, handles[0],
TRUE, 20000*maxThreads);

但是 WaitForMultipleObjects 总是返回 WAIT_FAILED,并且 GetLastError 产生 6 无效句柄。 AfxBeginThread 返回的测试不足以保证线程已成功创建并且句柄有效,或者句柄在 WaitForMultipleObjects 调用之前变得无效,我认为可以通过设置 m_bAutoDeleteFALSE

当多个线程由 AfxBeginThread 创建时,是否有更好的方法来等待它们?

请注意,maxThreads=1 即可。

最佳答案

handles[0] 指向具有一个有效句柄和一些可能跟随它的数据的东西。 maxThreads 相反建议数组应该有两个句柄一个接一个。因此错误。

这就是你想要的:

HANDLE handles[maxThreads];
//...
handles[threadId] = threads[threadId]->m_hThread;
//...
WaitForMultipleObjects(maxThreads, handles, ...

关于c++ - 带有 CWinThread 指针数组的 WaitForMultipleObjects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12090863/

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