vc++创建多线程应用

构建线程参数结构体:

typedef struct 
{
    int nIndex;
    HANDLE hThread;
    int param1;
          ...
}ThreadParam;

创建线程数组:

ThreadParam threadParam[16];

创建一个线程,用来创建线程:

    CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)StartThread, threadParam, NULL, NULL);

创建线程函数体:

   //初始化线程
    for(int i = 0; i < 16; i++)
    {
        //初始化事件对象
        g_hEvent[i] = CreateEvent(NULL,//默认安全属性
            NULL,//设置为自动重置
            FALSE,//初始状态为无信号
            NULL);//匿名
        //初始化索引值
        threadParam[i].nIndex = i; 
        threadParam[i].hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadFunc,(LPVOID)&threadParam[i], NULL, NULL);
    }

线程函数:

int WINAPI TheadFunc(LPVOID lpParam)
{
    ThreadParam*  threadParam = (ThreadParam *) lpParam;
    int nIndex = threadParam->nIndex;
    int dwRtn;
    while(true)
    {
       WaitForSingleObject(g_hEvent[nIndex], INFINITE);
       do something ...
    }
    return dwRtn;
}

 

posted @ 2018-10-25 10:52  余生以学  阅读(2352)  评论(1编辑  收藏  举报