Take a look:
Simplest ThreadPool example Using C++[
^]
What is ThreadPool?
Thread Pool is collection of Live, Reusable threads.
Why ThreadPool?
There are many situation where we can use ThreadPool. Consider a Client-Server application in which server has to respond to multiple client at same time. This means multitasking. Server will need a set of certain no. of threads which will do reply to client.
The big advantage of thread pool is that, it provides reusable thread. Though thread creation is very bulky process. It increases overhead. Suppose a new client send some data to server and Server has to respond. What will server do? It will create a new thread which will send data to client and then get killed or exited. Instead of creating thread on each client request we can keep collection of live thread. We will use any free thread which will send data to client. By that we will save a great overhead generated by creating threads multiple times. ...
void CThreadPoolMgr::Initialize(int nThread)
{
m_nThreadCount = nThread;
int nCounter = 0;
int nThreadCount = m_nThreadCount - 1;
while( nCounter <= nThreadCount )
{
m_ptrCThread[nCounter] = new CThread();
m_ptrCThread[nCounter]->CreateWorkerThread();
m_hThreadPool[nCounter] = m_ptrCThread[nCounter]->GetThreadHandle();
nCounter++;
}
}
void CThreadPoolMgr::ShutDown()
{
int Count = 0;
while(Count <= (m_nThreadCount - 1))
{
m_ptrCThread[Count]->SignalShutDownEvent();
Count++;
}
DWORD dwWaitResult = WaitForMultipleObjects( GetThreadCount(), m_hThreadPool, TRUE, INFINITE);
switch(dwWaitResult)
{
case WAIT_OBJECT_0:
{
cout << "All threads are ended.\n";
Count = 0;
while( Count <= (m_nThreadCount - 1))
{
m_ptrCThread[Count]->ReleaseHandles();
delete m_ptrCThread[Count];
Count++;
}
break;
}
default:
cout << "Wait Error: " << GetLastError() << "\n";
}
}