线程池

// MultiThread1.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <windows.h>


#define  THREADMAX 1000


//线程信息类
class ThreadInfo
{
public:
DWORD dwIndex;//当前线程在线程池中的索引号[0,THREADMAX)
DWORD dwThreadID;//当前线程的ID号码
DWORD dwCounter;//当前线程的使用计数,递增
HANDLE hThread;//当前线程的句柄
public:
ThreadInfo()
{
dwIndex = 0;
dwThreadID=0; 
dwCounter=0;
hThread=NULL;
}
virtual ~ThreadInfo()
{
if(hThread!=NULL) 
CloseHandle(hThread);
}
};


//全局变量:线程数组 和 临界区
ThreadInfo tinfo[THREADMAX];
CRITICAL_SECTION cs = {0};


//线程的执行部分
void funThread(ThreadInfo* pParam)
{
while (TRUE)
{
EnterCriticalSection(&cs);
ThreadInfo* pTemp = (ThreadInfo*)pParam;
printf("Thread ID: %d/%d \t counter: %d\r\n", GetCurrentThreadId(), pTemp->dwIndex, pTemp->dwCounter++);
Sleep(100); //每个线程空闲10ms
LeaveCriticalSection(&cs);
Sleep(1000);
}
}


//主函数:MAIN
int main(int argc, char* argv[])
{
//初始化临界区
InitializeCriticalSection(&cs);
int i = 0;
//创建线程 : THREADMAX个线程
for(i=0; i<THREADMAX; i++)
{
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)funThread, &tinfo[i], 0, &tinfo[i].dwThreadID);
tinfo[i].dwIndex = i;
}
while (1)
{ //让程序能够继续
/* EnterCriticalSection(&cs);
printf("Main id: %04d THREAD1: %04d THREAD2: %04d THREAD3: %04d\r\n", GetCurrentThreadId(), tinfo[0].dwThreadID, tinfo[1].dwThreadID, tinfo[2].dwThreadID);
LeaveCriticalSection(&cs);
*/ Sleep(1000);
}
return 0;
}


你可能感兴趣的:(thread,null,Class)