Interface如下
代码
struct Job
{
void (*func)(void*);
void *para;
};
class ThreadPool:noncopyable
{
public:
static SetNumThreads(size_t NThread); //MUST called before Instance()
static ThreadPool& Instance();
boost::shared_ptr<Event> SubmitJob(const Job& job);
void WaitAllJobDone();
//make as public JUST FOR pass VC6 compile!
ThreadPool();
~ThreadPool();
private:
static void JobThread( void * pThis );
bool m_exit;
std::vector<unsigned long> m_threads;
struct JobData
{
Job job;
boost::shared_ptr<Event> event;
};
std::list<JobData> m_JobQueue;
Mutex m_jobMutex;
static size_t m_numThread;
};
{
void (*func)(void*);
void *para;
};
class ThreadPool:noncopyable
{
public:
static SetNumThreads(size_t NThread); //MUST called before Instance()
static ThreadPool& Instance();
boost::shared_ptr<Event> SubmitJob(const Job& job);
void WaitAllJobDone();
//make as public JUST FOR pass VC6 compile!
ThreadPool();
~ThreadPool();
private:
static void JobThread( void * pThis );
bool m_exit;
std::vector<unsigned long> m_threads;
struct JobData
{
Job job;
boost::shared_ptr<Event> event;
};
std::list<JobData> m_JobQueue;
Mutex m_jobMutex;
static size_t m_numThread;
};
附加一个简单的使用例子
代码
void f(void* p)
{
int* pI = (int*)p;
printf("Thread %d, I: %d\n", GetCurrentThreadId(), *pI);
Sleep(1000);
}
int main(int argc, char* argv[])
{
printf("Hello World!\n");
ThreadPool& pool = ThreadPool::Instance();
size_t i;
std::vector<int> paras(10);
for(i=0; i<10; i++)
paras[i] = i;
Job job;
job.func = f;
//std::vector<boost::shared_ptr<Event> > jobs;
for(i=0; i<10; i++)
{
job.para = ¶s[i];
pool.SubmitJob(job);
//jobs.push_back();
}
/*for(i=0; i<10; i++)
{
jobs[i]->Wait(INFINITE);
}*/
pool.WaitAllJobDone();
{
int* pI = (int*)p;
printf("Thread %d, I: %d\n", GetCurrentThreadId(), *pI);
Sleep(1000);
}
int main(int argc, char* argv[])
{
printf("Hello World!\n");
ThreadPool& pool = ThreadPool::Instance();
size_t i;
std::vector<int> paras(10);
for(i=0; i<10; i++)
paras[i] = i;
Job job;
job.func = f;
//std::vector<boost::shared_ptr<Event> > jobs;
for(i=0; i<10; i++)
{
job.para = ¶s[i];
pool.SubmitJob(job);
//jobs.push_back();
}
/*for(i=0; i<10; i++)
{
jobs[i]->Wait(INFINITE);
}*/
pool.WaitAllJobDone();
全部源代码在这里 (vs6)