0
#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);
4

3 回答 3

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);
于 2013-07-05T09:03:26.627 回答
1

如果您的线程数较少,它会起作用吗?手册说如果你有超过 ,你需要做额外的工作,MAXIMUM_WAIT_OBJECTS特别是

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

请参阅此处进行讨论。

检查等待函数返回的内容可能也是值得的。

于 2013-07-05T09:27:40.517 回答
0

我会在调用 _beginthreadex 之前分配一个结构,并通过线程参数将指针传递给该结构,并让该结构包含一个由线程在完成时设置的布尔值。

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;
}
于 2013-07-05T10:20:05.267 回答