我有一个通过 生成线程的循环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_bAutoDelete为FALSE.
有没有更好的方法在创建多个线程时等待它们AfxBeginThread?
请注意,当maxThreads=1.