Files
cocosocket/cocosocket-client/ThreadPool.cpp
beykery c80c23cc3c unity
2014-10-31 10:39:13 +08:00

79 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <iostream>
#include "ThreadPool.h"
#include "Thread.h"
#include <semaphore.h>
using namespace std;
ThreadPool::ThreadPool(int poolsize)
: poolSize(poolsize), pool(NULL)
{
pool = new WorkThread* [poolsize];
for (int i = 0; i < poolsize; ++i)
{
pool[i] = new WorkThread();
}
}
ThreadPool::~ThreadPool()
{
if (NULL == pool)
{
return;
}
for (int i = 0; i < poolSize; ++i)
{
if (NULL == pool[i])
{
continue;
}
delete pool[i];
}
delete [] pool;
}
void ThreadPool::Offer(Thread * task)
{
bool result = false;
WorkThread* g = NULL;
for (int i = 0; i < poolSize; ++i)
{
if (pool[i]->GetStatus() == Thread::IDLE)
{
pool[i]->AddTask(task);
return;
} else if (g == NULL)
{
g = pool[i];
} else if (g->TaskCount() > pool[i]->TaskCount())
{
g = pool[i];
}
}
g->AddTask(task);
}
/**
* 停止线程池调用之后不能再往线程池里放task否则
*/
void ThreadPool::Shutdown()
{
if (NULL == pool)
{
return;
}
for (int i = 0; i < poolSize; ++i)
{
if (NULL == pool[i])
{
continue;
}
pool[i]->SetStatus(Thread::QUITED);
sem_post(pool[i]->GetSem());
pool[i]->Join();
delete pool[i];
pool[i] = NULL;
}
delete [] pool;
}