不到300行的简单线程池C++实现(一)

2014-11-24 12:22:38 · 作者: · 浏览: 8

///////////////// 头文件 Thread.h//////////////////////////////


/**************
Multi-threading-related Classes

2011-11-03 Add By AYA
Support Windows platform only

**************/
#ifndef THREAD_H_2011_11_03
#define THREAD_H_2011_11_03
#include
#include
#ifdef WIN32
#include
#endif


class ThreadException {
public:
ThreadException (const char* msg)
: mMsg (msg) {
}

const char* what () const {
return mMsg.c_str ();
}
private:
std::string mMsg;
};



///////////////// Lock & LockGuide //////////////////////////////
class Lock {
public:
Lock ();
~Lock ();

public:
void Enter ();
void Leave ();


private:
CRITICAL_SECTION mSection;
};


class LockGuide {
public:
LockGuide (Lock& _Lock)
:mLock (_Lock) {
mLock.Enter();
}

~LockGuide () {
mLock.Leave ();
}

private:
Lock& mLock;
};


/////////////// Signal ///////////////////////////////
class Signal {
public:
Signal ();
~Signal ();

public:
bool Wait (unsigned int Timeout = INFINITE);
void WakeUp ();

private:
HANDLE mHandle;
};


////////////// Job /////////////////////////////////

class Job {
public:
virtual void Do () = 0;
};



///////////////// Thread ///////////////////////////
class Thread {
friend class ThreadPool;
public:
Thread (ThreadPool& Pool);
virtual ~Thread ();

public:
void Attach (Job* _Job);

private:
/// Only called by ThreadPool
void Die ();

private:
static DWORD WINAPI Routine (LPVOID Parameter);

private:
DWORD mThreadID;
HANDLE mHandle;

Lock mLock;
Signal mSignal;
Signal mDieSignal;
Job* mCurrJob;
ThreadPool& mPool;
bool mIsDie;
};



///////////////// ThreadPool /////////////////////////
class ThreadPool {
friend class Thread;
public:
ThreadPool ();
~ThreadPool ();

public:
bool Alloc (unsigned int ThreadNum);
bool IsBusy ();
void Release (); /// WARNING: ALL THREADS MUST BE IDLE BEFORE RELEASE THE POOL!
Thread* Get ();


private:
/// Only called by Thread
void Put (Thread* _Thread);


private:
Lock mKeeper;
std::list mIdleThreads;
std::list mBusyThreads;
};


#endif

/////////////////////实现 Thread.cpp///////////////////////////////////////

#include "Thread.h"

Lock::Lock()
{
InitializeCriticalSection (&mSection);
}

Lock::~Lock()
{
DeleteCriticalSection (&mSection);
}

void
Lock::Enter()
{
EnterCriticalSection (&mSection);
}

void
Lock::Leave()
{
LeaveCriticalSection (&mSection);
}



#undef _CLASS_
#define _CLASS_ "Signal"

Signal::Signal()
{
mHandle = CreateSemaphore (NULL, 0, 1, NULL);
if (!mHandle) {
throw ThreadException ("CreateSemaphore Failed");
}
}


Signal::~Signal()
{
CloseHandle (mHandle);
}


bool
Signal::Wait (eolas_uint Timeout)
{
if (WAIT_OBJECT_0 != WaitForSingleObject(mHandle, Timeout)) {
return false;
}
return true;
}


void
Signal::WakeUp ()
{
if (!ReleaseSemaphore(mHandle, 1, NULL)) {
throw ThreadException ("ReleaseSemaphore Failed");
}
}




#undef _CLASS_
#define _CLASS_ "Thread"


Thread::Thread(Thread