乙個簡單的執行緒池實現

2021-07-24 03:09:14 字數 2288 閱讀 4046

乙個linux下簡單的執行緒池實現

實現了大部分邏輯,有部分邏輯未實現,只是提供乙個思路

執行緒池類

/*

* threadpool.h

* * created on: oct 13, 2016

* author: luokun

*/#ifndef threadpool_h_

#define threadpool_h_

#include #include "task.h"

#include #include using namespace std;

class cthreadpool

;#endif /* threadpool_h_ */

#include "threadpool.h"

#include #include const int defult_time = 30;

cthreadpool::cthreadpool()

cthreadpool::~cthreadpool()

void cthreadpool::addtaskintopool(ctask* task)

if(shutdown)

//操作任務,加任務鎖

m_deque.push_back(task); //位部新增

curenttasksize++;

pthread_cond_signal(&q_not_empty); //提示其他執行緒,由資料可以處理

pthread_mutex_unlock(&lockthread);

}//任務處理

void *doworktask(void* args)

}if(pool->shutdown)

ctask* a = (pool->m_deque).at(0) ; //取得最先放入佇列的資料

deque ::iterator it = pool->m_deque.begin();

it = pool->m_deque.erase(it);

pthread_cond_signal(&(pool->q_not_full));

pool->curenttasksize--;

pthread_mutex_unlock(&(pool->lockthread));

a->run();

delete a;

}}//執行緒管理

void* domangethread(void* args)

pool->killthreadsize = curthreadsize - minusesize;

}else if(addthreadsize> 0)

addthreadsize = maxusesize - curthreadsize;

for(int i = 0; i < addthreadsize; i++)

}else

pthread_mutex_unlock(&(pool->lockthread)); }}

void cthreadpool::poolinit(int usethreadsize)

pthread_t mangethid;

pthread_create(&mangethid,null,domangethread,(void*)this);

}

任務類是個父類,可以新增子類實現

/*

* task.h

* * created on: oct 14, 2016

* author: luokun

*/#ifndef task_h_

#define task_h_

class ctask

; int m;

virtual ~ctask(){};

virtual void run();

};#endif /* task_h_ */

/* * task.cpp

* * created on: oct 14, 2016

* author: luokun

*/#include "task.h"

#include #include using namespace std;

void ctask::run()

}

執行緒池(一) 實現乙個簡單的執行緒池

我們知道頻繁的建立 銷毀執行緒是不可取的,為了減少建立和銷毀執行緒的次數,讓每個執行緒可以多次使用,我們就可以使用執行緒池,可以降低資源到的消耗。執行緒池裡面肯定有多個執行緒,那麼我們就簡單的用乙個陣列來儲存執行緒,那我們我們預設裡面有 5 個執行緒。那我們執行緒池裡只有五個執行緒能同時工作,那同時...

乙個執行緒池的簡單的實現

執行緒池實現 用於執行大量相對短暫的任務 當任務增加的時候能夠動態的增加執行緒池中線程的數量直到達到乙個閾值。當任務執行完畢的時候,能夠動態的銷毀執行緒池中的執行緒 該執行緒池的實現本質上也是生產者與消費模型的應用。生產者執行緒向任務佇列中新增任務,一旦佇列有任務到來,如果有等待執行緒就喚醒來執行任...

Linux C 乙個執行緒池的簡單實現

這是對pthread執行緒的乙個簡單應用 1.實現了執行緒池的概念,執行緒可以重複使用。2.對訊號量,互斥鎖等進行封裝,業務處理函式中只需寫和業務相關的 3.移植性好。如果想把這個執行緒池 應用到自己的實現中去,只要寫自己的業務處理函式和改寫工作佇列資料的處理方法就可以了。sample 主要包括乙個...