#include <windows.h>
#include <cstdio>
#include <process.h>#define MY_MSG WM_USER+100
const int MAX_INFO_SIZE = 20;HANDLE hStartEvent; // thread start event
/*
要把SETTING 改为多线程的 
Project->Settings->C/C++, 
在Category 中选Code Generation, 然后在Use run-time libray 中选一个 
Multithread 配置 

*/
// thread function#include <queue>
using namespace std;queue<int> g_test;unsigned __stdcall fun(void *param)
{
    printf("thread fun start\n");

hStartEvent = ::CreateEvent(0,FALSE,FALSE,0); //create thread start event
    if(hStartEvent == 0)
    {
        printf("create start event failed,errno:%d\n",::GetLastError());
        return 1;
    }    
    while(true)
    {
//wait thread start event to avoid PostThreadMessage return errno:1444
::WaitForSingleObject(hStartEvent,INFINITE);
printf("收到信号...,%d\n",g_test.front());
g_test.pop();
       
    }
    return 0;
}int main()
{
    HANDLE hThread;
    unsigned nThreadID;
    //start thread
    hThread = (HANDLE)_beginthreadex( NULL, 0, &fun, NULL, 0, &nThreadID );
    if(hThread == 0)
    {
        printf("start thread failed,errno:%d\n",::GetLastError());
        CloseHandle(hStartEvent);
        return 1;
    }    int count = 0;
    while(true)
    {
g_test.push(++count);
if(!SetEvent(hStartEvent)) //set thread start event 
{
printf("set start event failed,errno:%d\n",::GetLastError());
//return 1;
}
if (count>10)
{
//::Sleep(5000);
}
        ::Sleep(50);
    }
 
CloseHandle(hStartEvent);
    CloseHandle(hThread);
    return 0;
}

解决方案 »

  1.   

    不严格的说,没问题。
    但你的EVENT最好是在main里创建,否则“可能”会先收到“set start event failed,errno”
    另外:
    if(hThread == 0)
        {
            printf("start thread failed,errno:%d\n",::GetLastError());
            CloseHandle(hStartEvent);
            return 1;
        }
    如果线程创建未遂,这个CloseHandle引入的也是一个INVALID HANDLE,所以在main里创建event这两个问题都可以解决。
      

  2.   

    1. 下面代码放到主线程中。 Create/Close注意对应
      hStartEvent = ::CreateEvent(0,FALSE,FALSE,0); //create thread start event
        if(hStartEvent == 0)
        {
            printf("create start event failed,errno:%d\n",::GetLastError());
            return 1;
        }    2.主线程结束时,最好等待工作线程结束    CloseHandle(hStartEvent);
        ::WaitForSingleObject(hThread,INFINITE);
        CloseHandle(hThread);