C ++等待所有线程完成

时间:2013-07-05 08:51:24

标签: c++ multithreading winapi events wait

#include <stdio.h>
#include <process.h>
#include <wtypes.h>
typedef unsigned int (__stdcall * THREAD_FUN_TYPE)(void *);

int ThreadIp(void* param)
{
    while(true)
    {
        printf("I'm runing!\n");
    }
    return 0;
}


int main()
{
    int iThreadNum=100;
    HANDLE* phThreads = new HANDLE[iThreadNum];
    for (int i=0;i<iThreadNum;++i)
    {
        phThreads[i]=(HANDLE*)_beginthreadex(NULL, 0,  (THREAD_FUN_TYPE)ThreadIp,NULL, NULL, NULL);
    }

    int nIndex = ::WaitForMultipleObjects(iThreadNum,phThreads,1,INFINITE);
    printf("End!\n");
    return 0;
}

我希望程序在WaitForMultipleObjects停止,直到所有线程都结束(直到所有线程都成功创建)。但程序不会在WaitForMultipleObjects停止,而所有线程仍在运行。所以我尝试使用SetEvent,但仍然存在同样的问题:

int iThreadNum=100;
HANDLE* phThreads = new HANDLE[iThreadNum];
for (int i=0;i<iThreadNum;++i)
{
    phThreads[i]=CreateEvent(NULL, FALSE, FALSE,NULL);
    ResetEvent(phThreads[i]);
}
int nIndex = ::WaitForMultipleObjects(iThreadNum,phThreads,1,INFINITE);

3 个答案:

答案 0 :(得分:2)

您应该等待线程句柄,而不是无关事件:

尝试这样的事情:

 int iThreadNum=100;
 HANDLE* phThreads = new HANDLE[iThreadNum];
 for (int i=0;i<iThreadNum;++i)
 {
     m_iCurThreadNum=i;
     phThreads[i] = _beginthreadex(...);
  }

 int nIndex = ::WaitForMultipleObjects(iThreadNum,phThreads,1,INFINITE);

答案 1 :(得分:1)

如果线程较少,它是否有效? manual表示如果您的MAXIMUM_WAIT_OBJECTS超过{{1}},则需要额外完成工作

  

nCount [in]指向的数组中的对象句柄数   lpHandles。对象句柄的最大数量是   MAXIMUM_WAIT_OBJECTS。此参数不能为零。

See here进行讨论。

也许值得检查等待函数返回的内容。

答案 2 :(得分:0)

我会在调用_beginthreadex之前分配一个struct,并通过threads参数将指针传递给struct,并让struct包含一个bool,它在完成时由线程设置。

struct ThreadStruct{
    bool Done;
    char* ParamData;
    int ParamDataSize;
};

int ThreadIp(void* param)
{
    ThreadStruct* ts = (ThreadStruct*)param;
    while(true)
    {
        printf("I'm runing!\n");
    }
    ts->Done = true;
    return 0;
}

int main()
{
    int iThreadNum=100;
    HANDLE* phThreads = new HANDLE[iThreadNum];
    ThreadStruct* structs = new ThreadStruct[iThreadNum];
    for (int i=0;i<iThreadNum;++i)
    {
        ZeroMemory(structs[i], sizeof(ThreadStruct));
        phThreads[i]=(HANDLE*)_beginthreadex(NULL, 0,  (THREAD_FUN_TYPE)ThreadIp, structs[i], NULL, NULL);
        ResetEvent(phThreads[i]);
    }

    for(unsigned int i=0; i<iThreadNum;){
        if(!structs[i]->Done) i=0;
        else i++;
    }
    printf("End!\n");
    return 0;
}