线程池(简单介绍及使用示例)
http://blog.csdn.net/loveghb/archive/2005/12/26/562657.aspx
线程池(简单介绍及使用示例)
Alt7提供了很多有用的工具,线城池就是其中的一个!既然已经有了。那我们就不要从轮子开始制造了,我们来看看怎么使用它吧。
template <class Worker,
class ThreadTraits = DefaultThreadTraits>
class CThreadPool : public IThreadPoolConfig
Worker是线程池队列里的一个工作线程,它需要遵循一个原形,如下:
Method
Description
Initialize
Called to initialize the worker object before any requests are passed to Execute.
Execute
Called to process a work item.
Terminate
Called to uninitialize the worker object after all requests have been passed to Execute.
Typedef
Description
RequestType
A typedef for the type of work item that can be processed by the worker class.
ThreadTraits 决定了如何创建线程
我写了个简单的demo,说明如何使用CThreadPool
//MyWorker.h
#ifndef _MYWORKER_H
#define _MYWORKER_H
#include <atlstr.h>
#include <iostream>
#include <atlsync.h>
using namespace std;
class CMyWorker
{
public:
typedef DWORD_PTR RequestType;
BOOL Initialize(void* pvWorkerParam)
{
CCriticalSection *pSec = (CCriticalSection *)pvWorkerParam;
pSec->Enter();
cout << "Initialize " << "Thread Id: " << GetCurrentThreadId() << endl;
pSec->Leave();
return TRUE;
}
void Execute(RequestType request, void* pvWorkerParam, OVERLAPPED* pOverlapped)
{
CCriticalSection *pSec = (CCriticalSection *)pvWorkerParam;
pSec->Enter();
cout << "Thread Id: " << GetCurrentThreadId() << " Message: " << (char *)request << endl;
pSec->Leave();
}
void Terminate(void* pvWorkerParam)
{
CCriticalSection *pSec = (CCriticalSection *)pvWorkerParam;
pSec->Enter();
cout << "Terminate " << "Thread Id: " << GetCurrentThreadId() << endl;
pSec->Leave();
}
};
#endif
//测试程序
#include "stdafx.h"
#include "MyWorker.h"
#include <iostream>
#include <atlutil.h>
#include <atlsync.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
CCriticalSection sec;
const JobCount = 10;
CThreadPool<CMyWorker> pool;
HRESULT hr=pool.Initialize(&sec,3);
long TimeOut;
pool.GetTimeout((DWORD *)&TimeOut);
cout << "TimeOut: " << TimeOut << endl; //默认是36秒
if (S_OK != hr)
{
cout << "Initialize failed!" << endl;
}
char *pStr[JobCount];
for (int i=0; i<JobCount; i++)
{
pStr[i] = new char[100];
memset(pStr[i], 0, 100);
itoa(i, pStr[i], 100);
pool.QueueRequest( (CMyWorker::RequestType)pStr[i] );
}
pool.Shutdown();
for (int j=0; j<JobCount; j++)
delete pStr[j];
return 0;
}
打印结果如下:
Initialize Thread Id: 1728
Initialize Thread Id: 1076
Initialize Thread Id: 3392
TimeOut: 36000
Thread Id: 3392 Message: 2
Thread Id: 1076 Message: 0
Thread Id: 1728 Message: 1
Thread Id: 3392 Message: 3
Thread Id: 1076 Message: 4
Thread Id: 3392 Message: 6
Thread Id: 1076 Message: 7
Thread Id: 1728 Message: 8
Thread Id: 3392 Message: 9
Atl7提供的线程池的默认的线程等待时间是36秒,线程池中默认的线程数是2个。