hi,
I am creating a ThreadPool. I know that thread pool is collection of live threads. Its main purpose is to assign task to any of available thread. I am not going through any complex tutorial available on net. So I am just creating threadpool by my own.
For this I have created a class with following property
ThreadPoolMgr.h
class CThreadPoolMgr
{
public:
CThreadPoolMgr(void);
public:
~CThreadPoolMgr(void);
private:
HANDLE m_hThreadArray[5];
DWORD m_ThreadID[5];
HANDLE m_hMutex; // Handle to mutex object
public:
void Run(void); // Function which will get executed by thread
static DWORD WINAPI ThreadProc(LPVOID Param); // Thread procedure
void Initialize(int nThread);
HANDLE GetMutex(void);
};
ThreadPoolMgr.cpp
CThreadPoolMgr::CThreadPoolMgr(void)
{
m_hMutex = NULL;
int cnt = 0;
while(cnt <= 4)
{
// Initialize members
m_hThreadArray[cnt] = NULL;
m_ThreadID[cnt] = 0;
cnt++;
}
}
CThreadPoolMgr::~CThreadPoolMgr(void)
{
}
void CThreadPoolMgr::Run(void)
{
cout << "Thread " << GetCurrentThreadId() <<" is Running.\n";
}
DWORD WINAPI CThreadPoolMgr::ThreadProc(LPVOID Param)
{
// Create object of ThreadPoolMgr
CThreadPoolMgr* objPool = (CThreadPoolMgr*)Param;
//prevent to call Run function from all thread at a same time
DWORD dwWaitResult = WaitForSingleObject( objPool->GetMutex(), INFINITE);
switch( dwWaitResult )
{
case WAIT_OBJECT_0:
// Call the Run function
objPool->Run();
// Now Release Mutex
if (! ReleaseMutex( objPool->GetMutex() ))
{
cout << "ReleaseMutex Error: " << GetLastError() << "\n";
}
break;
}
return 0;
}
void CThreadPoolMgr::Initialize(int nThread)
{
int nCounter = 0;
int nThreadCount = nThread - 1;
m_hMutex = CreateMutex(NULL, FALSE, L"MyMutex");
while( nCounter <= nThreadCount )
{
m_hThreadArray[nCounter] = CreateThread(NULL,NULL,ThreadProc,this,0,&m_ThreadID[nCounter]);
// Increment the counter
nCounter++;
}
DWORD dwWaitResult = WaitForMultipleObjects( nThread, m_hThreadArray, TRUE, INFINITE);
switch(dwWaitResult)
{
case WAIT_OBJECT_0:
cout << "All threads are ended.\n";
break;
default:
cout << "Wait Error: " << GetLastError() << "\n";
}
}
HANDLE CThreadPoolMgr::GetMutex( void )
{
return m_hMutex;
}
Though it is not completed fully. I have some doubt
1. I need to keep thread alive means in threadproc control should not reach on return 0; statement. Here i need your guidance. I think here i need a while loop to prevent control to reach at return 0. Or should i use event to notify shutdown. But i dont know how to use event here.
2. Where i should place mutex - In threadproc or in Run function.