c++版線程池和義務池示例。本站提示廣大學習愛好者:(c++版線程池和義務池示例)文章只能為提供參考,不一定能成為您想要的結果。以下是c++版線程池和義務池示例正文
commondef.h
//單元秒,監測余暇列表時光距離,在余暇隊列中跨越TASK_DESTROY_INTERVAL時光的義務將被主動燒毀
const int CHECK_IDLE_TASK_INTERVAL = 300;
//單元秒,義務主動燒毀時光距離
const int TASK_DESTROY_INTERVAL = 60;
//監控線程池能否為空時光距離,微秒
const int IDLE_CHECK_POLL_EMPTY = 500;
//線程池線程余暇主動加入時光距離 ,5分鐘
const int THREAD_WAIT_TIME_OUT = 300;
taskpool.cpp
#include "taskpool.h"
#include <string.h>
#include <stdio.h>
#include <pthread.h>
TaskPool::TaskPool(const int & poolMaxSize)
: m_poolSize(poolMaxSize)
, m_taskListSize(0)
, m_bStop(false)
{
pthread_mutex_init(&m_lock, NULL);
pthread_mutex_init(&m_idleMutex, NULL);
pthread_cond_init(&m_idleCond, NULL);
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); // 讓線程自力運轉
pthread_create(&m_idleId, &attr, CheckIdleTask, this); //創立監測余暇義務過程
pthread_attr_destroy(&attr);
}
TaskPool::~TaskPool()
{
if(!m_bStop)
{
StopPool();
}
if(!m_taskList.empty())
{
std::list<Task*>::iterator it = m_taskList.begin();
for(; it != m_taskList.end(); ++it)
{
if(*it != NULL)
{
delete *it;
*it = NULL;
}
}
m_taskList.clear();
m_taskListSize = 0;
}
if(!m_idleList.empty())
{
std::list<Task*>::iterator it = m_idleList.begin();
for(; it != m_idleList.end(); ++it)
{
if(*it != NULL)
{
delete *it;
*it = NULL;
}
}
m_idleList.clear();
}
pthread_mutex_destroy(&m_lock);
pthread_mutex_destroy(&m_idleMutex);
pthread_cond_destroy(&m_idleCond);
}
void * TaskPool::CheckIdleTask(void * arg)
{
TaskPool * pool = (TaskPool*)arg;
while(1)
{
pool->LockIdle();
pool->RemoveIdleTask();
if(pool->GetStop())
{
pool->UnlockIdle();
break;
}
pool->CheckIdleWait();
pool->UnlockIdle();
}
}
void TaskPool::StopPool()
{
m_bStop = true;
LockIdle();
pthread_cond_signal(&m_idleCond); //避免監控線程正在期待,而惹起沒法加入的成績
UnlockIdle();
pthread_join(m_idleId, NULL);
}
bool TaskPool::GetStop()
{
return m_bStop;
}
void TaskPool::CheckIdleWait()
{
struct timespec timeout;
memset(&timeout, 0, sizeof(timeout));
timeout.tv_sec = time(0) + CHECK_IDLE_TASK_INTERVAL;
timeout.tv_nsec = 0;
pthread_cond_timedwait(&m_idleCond, &m_idleMutex, &timeout);
}
int TaskPool::RemoveIdleTask()
{
int iRet = 0;
std::list<Task*>::iterator it, next;
std::list<Task*>::reverse_iterator rit = m_idleList.rbegin();
time_t curTime = time(0);
for(; rit != m_idleList.rend(); )
{
it = --rit.base();
if(difftime(curTime,((*it)->last_time)) >= TASK_DESTROY_INTERVAL)
{
iRet++;
delete *it;
*it = NULL;
next = m_idleList.erase(it);
rit = std::list<Task*>::reverse_iterator(next);
}
else
{
break;
}
}
}
int TaskPool::AddTask(task_fun fun, void *arg)
{
int iRet = 0;
if(0 != fun)
{
pthread_mutex_lock(&m_lock);
if(m_taskListSize >= m_poolSize)
{
pthread_mutex_unlock(&m_lock);
iRet = -1; //task pool is full;
}
else
{
pthread_mutex_unlock(&m_lock);
Task * task = GetIdleTask();
if(NULL == task)
{
task = new Task;
}
if(NULL == task)
{
iRet = -2; // new failed
}
else
{
task->fun = fun;
task->data = arg;
pthread_mutex_lock(&m_lock);
m_taskList.push_back(task);
++m_taskListSize;
pthread_mutex_unlock(&m_lock);
}
}
}
return iRet;
}
Task* TaskPool::GetTask()
{
Task *task = NULL;
pthread_mutex_lock(&m_lock);
if(!m_taskList.empty())
{
task = m_taskList.front();
m_taskList.pop_front();
--m_taskListSize;
}
pthread_mutex_unlock(&m_lock);
return task;
}
void TaskPool::LockIdle()
{
pthread_mutex_lock(&m_idleMutex);
}
void TaskPool::UnlockIdle()
{
pthread_mutex_unlock(&m_idleMutex);
}
Task * TaskPool::GetIdleTask()
{
LockIdle();
Task * task = NULL;
if(!m_idleList.empty())
{
task = m_idleList.front();
m_idleList.pop_front();
}
UnlockIdle();
return task;
}
void TaskPool::SaveIdleTask(Task*task)
{
if(NULL != task)
{
task->fun = 0;
task->data = NULL;
task->last_time = time(0);
LockIdle();
m_idleList.push_front(task);
UnlockIdle();
}
}
taskpool.h
#ifndef TASKPOOL_H
#define TASKPOOL_H
/* purpose @ 義務池,重要是緩沖內部高並發義務數,有manager擔任調劑義務
* 義務池可主動燒毀長時光余暇的Task對象
* 可經由過程CHECK_IDLE_TASK_INTERVAL設置檢討idle余暇過程輪訓期待時光
* TASK_DESTROY_INTERVAL 設置Task余暇時光,跨越這個時光值將會被CheckIdleTask線程燒毀
* date @ 2013.12.23
* author @ haibin.wang
*/
#include <list>
#include <pthread.h>
#include "commondef.h"
//一切的用戶操作為一個task,
typedef void (*task_fun)(void *);
struct Task
{
task_fun fun; //義務處置函數
void* data; //義務處置數據
time_t last_time; //參加余暇隊列的時光,用於主動燒毀
};
//義務池,一切義務會送達就任務池中,治理線程擔任將義務送達給線程池
class TaskPool
{
public:
/* pur @ 初始化義務池,啟動義務池余暇隊列主動燒毀線程
* para @ maxSize 最年夜義務數,年夜於0
*/
TaskPool(const int & poolMaxSize);
~TaskPool();
/* pur @ 添加義務就任務隊列的尾部
* para @ task, 詳細義務
* return @ 0 添加勝利,正數 添加掉敗
*/
int AddTask(task_fun fun, void* arg);
/* pur @ 從義務列表的頭獲得一個義務
* return @ 假如列表中有義務則前往一個Task指針,不然前往一個NULL
*/
Task* GetTask();
/* pur @ 保留余暇義務到余暇隊列中
* para @ task 已被挪用履行的義務
* return @
*/
void SaveIdleTask(Task*task);
void StopPool();
public:
void LockIdle();
void UnlockIdle();
void CheckIdleWait();
int RemoveIdleTask();
bool GetStop();
private:
static void * CheckIdleTask(void *);
/* pur @ 獲得余暇的task
* para @
* para @
* return @ NULL解釋沒有余暇的,不然從m_idleList中獲得一個
*/
Task* GetIdleTask();
int GetTaskSize();
private:
int m_poolSize; //義務池年夜小
int m_taskListSize; // 統計taskList的年夜小,由於當List的年夜小會跟著數目的增多而耗時增長
bool m_bStop; //能否停滯
std::list<Task*> m_taskList;//一切待處置義務列表
std::list<Task*> m_idleList;//一切余暇義務列表
pthread_mutex_t m_lock; //對義務列表停止加鎖,包管每次只能取一個義務
pthread_mutex_t m_idleMutex; //余暇義務隊列鎖
pthread_cond_t m_idleCond; //余暇隊列期待前提
pthread_t m_idleId;;
};
#endif
threadpool.cpp
/* purpose @ 線程池類,擔任線程的創立與燒毀,完成線程超時主動加入功效(半駐留)
* date @ 2014.01.03
* author @ haibin.wang
*/
#include "threadpool.h"
#include <errno.h>
#include <string.h>
/*
#include <iostream>
#include <stdio.h>
*/
Thread::Thread(bool detach, ThreadPool * pool)
: m_pool(pool)
{
pthread_attr_init(&m_attr);
if(detach)
{
pthread_attr_setdetachstate(&m_attr, PTHREAD_CREATE_DETACHED ); // 讓線程自力運轉
}
else
{
pthread_attr_setdetachstate(&m_attr, PTHREAD_CREATE_JOINABLE );
}
pthread_mutex_init(&m_mutex, NULL); //初始化互斥量
pthread_cond_init(&m_cond, NULL); //初始化前提變量
task.fun = 0;
task.data = NULL;
}
Thread::~Thread()
{
pthread_cond_destroy(&m_cond);
pthread_mutex_destroy(&m_mutex);
pthread_attr_destroy(&m_attr);
}
ThreadPool::ThreadPool()
: m_poolMax(0)
, m_idleNum(0)
, m_totalNum(0)
, m_bStop(false)
{
pthread_mutex_init(&m_mutex, NULL);
pthread_mutex_init(&m_runMutex,NULL);
pthread_mutex_init(&m_terminalMutex, NULL);
pthread_cond_init(&m_terminalCond, NULL);
pthread_cond_init(&m_emptyCond, NULL);
}
ThreadPool::~ThreadPool()
{
/*if(!m_threads.empty())
{
std::list<Thread*>::iterator it = m_threads.begin();
for(; it != m_threads.end(); ++it)
{
if(*it != NULL)
{
pthread_cond_destroy( &((*it)->m_cond) );
pthread_mutex_destroy( &((*it)->m_mutex) );
delete *it;
*it = NULL;
}
}
m_threads.clear();
}*/
pthread_mutex_destroy(&m_runMutex);
pthread_mutex_destroy(&m_terminalMutex);
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_terminalCond);
pthread_cond_destroy(&m_emptyCond);
}
int ThreadPool::InitPool(const int & poolMax, const int & poolPre)
{
if(poolMax < poolPre
|| poolPre < 0
|| poolMax <= 0)
{
return -1;
}
m_poolMax = poolMax;
int iRet = 0;
for(int i=0; i<poolPre; ++i)
{
Thread * thread = CreateThread();
if(NULL == thread)
{
iRet = -2;
}
}
if(iRet < 0)
{
std::list<Thread*>::iterator it = m_threads.begin();
for(; it!= m_threads.end(); ++it)
{
if(NULL != (*it) )
{
delete *it;
*it = NULL;
}
}
m_threads.clear();
m_totalNum = 0;
}
return iRet;
}
void ThreadPool::GetThreadRun(task_fun fun, void* arg)
{
//從線程池中獲得一個線程
pthread_mutex_lock( &m_mutex);
if(m_threads.empty())
{
pthread_cond_wait(&m_emptyCond,&m_mutex); //壅塞期待有余暇線程
}
Thread * thread = m_threads.front();
m_threads.pop_front();
pthread_mutex_unlock( &m_mutex);
pthread_mutex_lock( &thread->m_mutex );
thread->task.fun = fun;
thread->task.data = arg;
pthread_cond_signal(&thread->m_cond); //觸發線程WapperFun輪回履行
pthread_mutex_unlock( &thread->m_mutex );
}
int ThreadPool::Run(task_fun fun, void * arg)
{
pthread_mutex_lock(&m_runMutex); //包管每次只能由一個線程履行
int iRet = 0;
if(m_totalNum <m_poolMax) //
{
if(m_threads.empty() && (NULL == CreateThread()) )
{
iRet = -1;//can not create new thread!
}
else
{
GetThreadRun(fun, arg);
}
}
else
{
GetThreadRun(fun, arg);
}
pthread_mutex_unlock(&m_runMutex);
return iRet;
}
void ThreadPool::StopPool(bool bStop)
{
m_bStop = bStop;
if(bStop)
{
//啟動監控一切余暇線程能否加入的線程
Thread thread(false, this);
pthread_create(&thread.m_threadId,&thread.m_attr, ThreadPool::TerminalCheck , &thread); //啟動監控一切線程加入線程
//壅塞期待一切余暇線程加入
pthread_join(thread.m_threadId, NULL);
}
/*if(bStop)
{
pthread_mutex_lock(&m_terminalMutex);
//啟動監控一切余暇線程能否加入的線程
Thread thread(true, this);
pthread_create(&thread.m_threadId,&thread.m_attr, ThreadPool::TerminalCheck , &thread); //啟動監控一切線程加入線程
//壅塞期待一切余暇線程加入
pthread_cond_wait(&m_terminalCond, & m_terminalMutex);
pthread_mutex_unlock(&m_terminalMutex);
}*/
}
bool ThreadPool::GetStop()
{
return m_bStop;
}
Thread * ThreadPool::CreateThread()
{
Thread * thread = NULL;
thread = new Thread(true, this);
if(NULL != thread)
{
int iret = pthread_create(&thread->m_threadId,&thread->m_attr, ThreadPool::WapperFun , thread); //經由過程WapperFun將線程參加到余暇隊列中
if(0 != iret)
{
delete thread;
thread = NULL;
}
}
return thread;
}
void * ThreadPool::WapperFun(void*arg)
{
Thread * thread = (Thread*)arg;
if(NULL == thread || NULL == thread->m_pool)
{
return NULL;
}
ThreadPool * pool = thread->m_pool;
pool->IncreaseTotalNum();
struct timespec abstime;
memset(&abstime, 0, sizeof(abstime));
while(1)
{
if(0 != thread->task.fun)
{
thread->task.fun(thread->task.data);
}
if( true == pool->GetStop() )
{
break; //肯定以後義務履行終了後再剖斷能否加入線程
}
pthread_mutex_lock( &thread->m_mutex );
pool->SaveIdleThread(thread); //將線程參加到余暇隊列中
abstime.tv_sec = time(0) + THREAD_WAIT_TIME_OUT;
abstime.tv_nsec = 0;
if(ETIMEDOUT == pthread_cond_timedwait( &thread->m_cond, &thread->m_mutex, &abstime )) //期待線程被叫醒 或超時主動加入
{
pthread_mutex_unlock( &thread->m_mutex );
break;
}
pthread_mutex_unlock( &thread->m_mutex );
}
pool->LockMutex();
pool->DecreaseTotalNum();
if(thread != NULL)
{
pool->RemoveThread(thread);
delete thread;
thread = NULL;
}
pool->UnlockMutex();
return 0;
}
void ThreadPool::SaveIdleThread(Thread * thread )
{
if(thread)
{
thread->task.fun = 0;
thread->task.data = NULL;
LockMutex();
if(m_threads.empty())
{
pthread_cond_broadcast(&m_emptyCond); //發送不空的旌旗燈號,告知run函數線程隊列曾經不空了
}
m_threads.push_front(thread);
UnlockMutex();
}
}
int ThreadPool::TotalThreads()
{
return m_totalNum;
}
void ThreadPool::SendSignal()
{
LockMutex();
std::list<Thread*>::iterator it = m_threads.begin();
for(; it!= m_threads.end(); ++it)
{
pthread_mutex_lock( &(*it)->m_mutex );
pthread_cond_signal(&((*it)->m_cond));
pthread_mutex_unlock( &(*it)->m_mutex );
}
UnlockMutex();
}
void * ThreadPool::TerminalCheck(void* arg)
{
Thread * thread = (Thread*)arg;
if(NULL == thread || NULL == thread->m_pool)
{
return NULL;
}
ThreadPool * pool = thread->m_pool;
while((false == pool->GetStop()) || pool->TotalThreads() >0 )
{
pool->SendSignal();
usleep(IDLE_CHECK_POLL_EMPTY);
}
//pool->TerminalCondSignal();
return 0;
}
void ThreadPool::TerminalCondSignal()
{
pthread_cond_signal(&m_terminalCond);
}
void ThreadPool::RemoveThread(Thread* thread)
{
m_threads.remove(thread);
}
void ThreadPool::LockMutex()
{
pthread_mutex_lock( &m_mutex);
}
void ThreadPool::UnlockMutex()
{
pthread_mutex_unlock( &m_mutex );
}
void ThreadPool::IncreaseTotalNum()
{
LockMutex();
m_totalNum++;
UnlockMutex();
}
void ThreadPool::DecreaseTotalNum()
{
m_totalNum--;
}
threadpool.h
#ifndef THREADPOOL_H
#define THREADPOOL_H
/* purpose @ 線程池類,擔任線程的創立與燒毀,完成線程超時主動加入功效(半駐留)a
* 當線程池加入時創立TerminalCheck線程,擔任監測線程池一切線程加入
* date @ 2013.12.23
* author @ haibin.wang
*/
#include <list>
#include <string>
#include "taskpool.h"
//經由過程threadmanager來掌握義務調劑過程
//threadpool的TerminalCheck線程擔任監測線程池一切線程加入
class ThreadPool;
class Thread
{
public:
Thread(bool detach, ThreadPool * pool);
~Thread();
pthread_t m_threadId; //線程id
pthread_mutex_t m_mutex; //互斥鎖
pthread_cond_t m_cond; //前提變量
pthread_attr_t m_attr; //線程屬性
Task task; //
ThreadPool * m_pool; //所屬線程池
};
//線程池,擔任創立線程處置義務,處置終了後會將線程參加到余暇隊列中,從義務池中
class ThreadPool
{
public:
ThreadPool();
~ThreadPool();
/* pur @ 初始化線程池
* para @ poolMax 線程池最年夜線程數
* para @ poolPre 預創立線程數
* return @ 0:勝利
* -1: parameter error, must poolMax > poolPre >=0
* -2: 創立線程掉敗
*/
int InitPool(const int & poolMax, const int & poolPre);
/* pur @ 履行一個義務
* para @ task 義務指針
* return @ 0義務分派勝利,負值 義務分派掉敗,-1,創立新線程掉敗
*/
int Run(task_fun fun, void* arg);
/* pur @ 設置能否停滯線程池任務
* para @ bStop true停滯,false一直止
*/
void StopPool(bool bStop);
public: //此私有函數重要用於靜態函數挪用
/* pur @ 獲得過程池的啟停狀況
* return @
*/
bool GetStop();
void SaveIdleThread(Thread * thread );
void LockMutex();
void UnlockMutex();
void DecreaseTotalNum();
void IncreaseTotalNum();
void RemoveThread(Thread* thread);
void TerminalCondSignal();
int TotalThreads();
void SendSignal();
private:
/* pur @ 創立線程
* return @ 非空 勝利,NULL掉敗,
*/
Thread * CreateThread();
/* pur @ 從線程池中獲得一個一個線程運轉義務
* para @ fun 函數指針
* para @ arg 函數參數
* return @
*/
void GetThreadRun(task_fun fun, void* arg);
static void * WapperFun(void*);
static void * TerminalCheck(void*);//輪回監測能否一切線程終止線程
private:
int m_poolMax;//線程池最年夜線程數
int m_idleNum; //余暇線程數
int m_totalNum; //以後線程總數 小於最年夜線程數
bool m_bStop; //能否停滯線程池
pthread_mutex_t m_mutex; //線程列表鎖
pthread_mutex_t m_runMutex; //run函數鎖
pthread_mutex_t m_terminalMutex; //終止一切線程互斥量
pthread_cond_t m_terminalCond; //終止一切線程前提變量
pthread_cond_t m_emptyCond; //余暇線程不空前提變量
std::list<Thread*> m_threads; // 線程列表
};
#endif
threadpoolmanager.cpp
#include "threadpoolmanager.h"
#include "threadpool.h"
#include "taskpool.h"
#include <errno.h>
#include <string.h>
/*#include <string.h>
#include <sys/time.h>
#include <stdio.h>*/
// struct timeval time_beg, time_end;
ThreadPoolManager::ThreadPoolManager()
: m_threadPool(NULL)
, m_taskPool(NULL)
, m_bStop(false)
{
pthread_mutex_init(&m_mutex_task,NULL);
pthread_cond_init(&m_cond_task, NULL);
/* memset(&time_beg, 0, sizeof(struct timeval));
memset(&time_end, 0, sizeof(struct timeval));
gettimeofday(&time_beg, NULL);*/
}
ThreadPoolManager::~ThreadPoolManager()
{
StopAll();
if(NULL != m_threadPool)
{
delete m_threadPool;
m_threadPool = NULL;
}
if(NULL != m_taskPool)
{
delete m_taskPool;
m_taskPool = NULL;
}
pthread_cond_destroy( &m_cond_task);
pthread_mutex_destroy( &m_mutex_task );
/*gettimeofday(&time_end, NULL);
long total = (time_end.tv_sec - time_beg.tv_sec)*1000000 + (time_end.tv_usec - time_beg.tv_usec);
printf("manager total time = %d\n", total);
gettimeofday(&time_beg, NULL);*/
}
int ThreadPoolManager::Init(
const int &tastPoolSize,
const int &threadPoolMax,
const int &threadPoolPre)
{
m_threadPool = new ThreadPool();
if(NULL == m_threadPool)
{
return -1;
}
m_taskPool = new TaskPool(tastPoolSize);
if(NULL == m_taskPool)
{
return -2;
}
if(0>m_threadPool->InitPool(threadPoolMax, threadPoolPre))
{
return -3;
}
//啟動線程池
//啟動義務池
//啟動義務獲得線程,從義務池中赓續拿義務到線程池中
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
pthread_create(&m_taskThreadId, &attr, TaskThread, this); //創立獲得義務過程
pthread_attr_destroy(&attr);
return 0;
}
void ThreadPoolManager::StopAll()
{
m_bStop = true;
LockTask();
pthread_cond_signal(&m_cond_task);
UnlockTask();
pthread_join(m_taskThreadId, NULL);
//期待以後一切義務履行終了
m_taskPool->StopPool();
m_threadPool->StopPool(true); // 停滯線程池任務
}
void ThreadPoolManager::LockTask()
{
pthread_mutex_lock(&m_mutex_task);
}
void ThreadPoolManager::UnlockTask()
{
pthread_mutex_unlock(&m_mutex_task);
}
void* ThreadPoolManager::TaskThread(void* arg)
{
ThreadPoolManager * manager = (ThreadPoolManager*)arg;
while(1)
{
manager->LockTask(); //避免義務沒有履行終了發送了停滯旌旗燈號
while(1) //將義務隊列中的義務履行完再加入
{
Task * task = manager->GetTaskPool()->GetTask();
if(NULL == task)
{
break;
}
else
{
manager->GetThreadPool()->Run(task->fun, task->data);
manager->GetTaskPool()->SaveIdleTask(task);
}
}
if(manager->GetStop())
{
manager->UnlockTask();
break;
}
manager->TaskCondWait(); //期待有義務的時刻履行
manager->UnlockTask();
}
return 0;
}
ThreadPool * ThreadPoolManager::GetThreadPool()
{
return m_threadPool;
}
TaskPool * ThreadPoolManager::GetTaskPool()
{
return m_taskPool;
}
int ThreadPoolManager::Run(task_fun fun,void* arg)
{
if(0 == fun)
{
return 0;
}
if(!m_bStop)
{
int iRet = m_taskPool->AddTask(fun, arg);
if(iRet == 0 && (0 == pthread_mutex_trylock(&m_mutex_task)) )
{
pthread_cond_signal(&m_cond_task);
UnlockTask();
}
return iRet;
}
else
{
return -3;
}
}
bool ThreadPoolManager::GetStop()
{
return m_bStop;
}
void ThreadPoolManager::TaskCondWait()
{
struct timespec to;
memset(&to, 0, sizeof to);
to.tv_sec = time(0) + 60;
to.tv_nsec = 0;
pthread_cond_timedwait( &m_cond_task, &m_mutex_task, &to); //60秒超時
}
threadpoolmanager.h
#ifndef THREADPOOLMANAGER_H
#define THREADPOOLMANAGER_H
/* purpose @
* 根本流程:
* 治理線程池和義務池,先將義務參加義務池,然後由TaskThread擔任從義務池中將義務掏出放入到線程池中
* 根本功效:
* 1、任務線程可以在營業不忙的時刻主動加入部門長時光不應用的線程
* 2、義務池可以在營業不忙的時刻主動釋放長時光不應用的資本(可經由過程commondef.h修正)
* 3、當法式退時不再向義務池中添加義務,當義務池中一切義務履行終了後才加入相干法式(做到法式的平安加入)
* 線程資本:
* 假如不預分派任何處置線程的話,ThreadPool只要當有義務的時刻才現實創立須要的線程,最年夜線程創立數為用戶指定
* 當manager燒毀的時刻,manager會創立一個監控一切義務履行終了的監控線程,只要當一切義務履行終了後manager才燒毀
* 線程最年夜數為:1個TaskPool線程 + 1個manager義務調劑線程 + ThreadPool最年夜線程數 + 1個manager加入監控線程 + 1線程池一切線程加入監控線程
* 線程最小數為:1個TaskPool創立余暇義務資本燒毀監控線程 + 1個manager創立義務調劑線程
* 應用辦法:
* ThreadPoolManager manager;
* manager.Init(100000, 50, 5);//初始化一個義務池為10000,線程池最年夜線程數50,預創立5個線程的治理器
* manager.run(fun, data); //添加履行義務到manager中,fun為函數指針,data為fun須要傳入的參數,data可認為NULL
*
* date @ 2013.12.23
* author @ haibin.wang
*
* 具體參數掌握可以修正commondef.h中的相干變量值
*/
#include <pthread.h>
typedef void (*task_fun)(void *);
class ThreadPool;
class TaskPool;
class ThreadPoolManager
{
public:
ThreadPoolManager();
~ThreadPoolManager();
/* pur @ 初始化線程池與義務池,threadPoolMax > threadPoolPre > threadPoolMin >= 0
* para @ tastPoolSize 義務池年夜小
* para @ threadPoolMax 線程池最年夜線程數
* para @ threadPoolPre 預創立線程數
* return @ 0:初始化勝利,正數 初始化掉敗
* -1:創立線程池掉敗
* -2:創立義務池掉敗
* -3:線程池初始化掉敗
*/
int Init(const int &tastPoolSize,
const int &threadPoolMax,
const int &threadPoolPre);
/* pur @ 履行一個義務
* para @ fun 須要履行的函數指針
* para @ arg fun須要的參數,默許為NULL
* return @ 0 義務分派勝利,正數 義務分派掉敗
* -1:義務池滿
* -2:義務池new掉敗
* -3:manager曾經發送停滯旌旗燈號,不再吸收新義務
*/
int Run(task_fun fun,void* arg=NULL);
public: //以下public函數重要用於靜態函數挪用
bool GetStop();
void TaskCondWait();
TaskPool * GetTaskPool();
ThreadPool * GetThreadPool();
void LockTask();
void UnlockTask();
void LockFull();
private:
static void * TaskThread(void*); //義務處置線程
void StopAll();
private:
ThreadPool *m_threadPool; //線程池
TaskPool * m_taskPool; //義務池
bool m_bStop; // 能否終止治理器
pthread_t m_taskThreadId; // TaskThread線程id
pthread_mutex_t m_mutex_task;
pthread_cond_t m_cond_task;
};
#endif
main.cpp
#include <iostream>
#include <string>
#include "threadpoolmanager.h"
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
int seq = 0;
int billNum =0;
int inter = 1;
pthread_mutex_t m_mutex;
void myFunc(void*arg)
{
pthread_mutex_lock(&m_mutex);
seq++;
if(seq%inter == 0 )
{
cout << "fun 1=" << seq << endl;
}
if(seq>=1000000000)
{
cout << "billion" << endl;
seq = 0;
billNum++;
}
pthread_mutex_unlock(&m_mutex);
//sleep();
}
int main(int argc, char** argv)
{
if(argc != 6)
{
cout << "必需有5個參數 義務履行次數 義務池年夜小 線程池年夜小 預創立線程數 輸入距離" << endl;
cout << "eg: ./test 999999 10000 100 10 20" << endl;
cout << "上例代表創立一個距離20個義務輸入,義務池年夜小為10000,線程池年夜小為100,預創立10個線程,履行義務次數為:999999" << endl;
return 0;
}
double loopSize = atof(argv[1]);
int taskSize = atoi(argv[2]);
int threadPoolSize = atoi(argv[3]);
int preSize = atoi(argv[4]);
inter = atoi(argv[5]);
pthread_mutex_init(&m_mutex,NULL);
ThreadPoolManager manager;
if(0>manager.Init(taskSize, threadPoolSize, preSize))
{
cout << "初始化掉敗" << endl;
return 0;
}
cout << "*******************初始化完成*********************" << endl;
struct timeval time_beg, time_end;
memset(&time_beg, 0, sizeof(struct timeval));
memset(&time_end, 0, sizeof(struct timeval));
gettimeofday(&time_beg, NULL);
double i=0;
for(; i<loopSize; ++i)
{
while(0>manager.Run(myFunc,NULL))
{
usleep(100);
}
}
gettimeofday(&time_end, NULL);
long total = (time_end.tv_sec - time_beg.tv_sec)*1000000 + (time_end.tv_usec - time_beg.tv_usec);
cout << "total time =" << total << endl;
cout << "total num =" << i << " billion num=" << billNum<< endl;
cout << __FILE__ << "將封閉一切線程" << endl;
//pthread_mutex_destroy(&m_mutex);
return 0;
}