#include<thread>
#include<mutex>
#include<vector>
#include<iostream>
#include<string>
#include<deque>
using namespace std;
namespace Z1 {
class Task
{
public:
Task(void* arg = NULL, const std::string taskName = "")
: arg_(arg)
, taskName_(taskName)
{
}
virtual ~Task()
{
}
void setArg(void* arg)
{
arg_ = arg;
}
virtual int run() = 0;
protected:
void* arg_;
std::string taskName_;
};
class ThreadPool{
private:
volatile bool isRunning_;//volatile的變量是說這變量可能會(huì)被意想不到地改變,這樣,編譯器就不會(huì)去假設(shè)這個(gè)變量的值了。
int threadNum_;
pthread_t* threads_;
deque<Task *> taskDeque_;
pthread_mutex_t mutex_;
pthread_cond_t condition_;
public:
ThreadPool(int threadNum = 10);
~ThreadPool();
size_t addTask(Task* task);
void stop();
int size();
Task* take();
private:
int createThreads();
static void* threadFunc(void * threadData);
private:
ThreadPool& operator=(const ThreadPool&);
ThreadPool(const ThreadPool&);
};
}
#include<threadpool.h>
#include<assert.h>
namespace Z1 {
ThreadPool::ThreadPool(int threadNum)
{
isRunning_ = true;
threadNum_ = threadNum;
createThreads();
}
ThreadPool::~ThreadPool()
{
stop();
deque<Task *>::iterator pd;
for(pd = taskDeque_.begin();pd != taskDeque_.end();++pd)
delete *pd;
taskDeque_.clear();
}
int ThreadPool::createThreads()
{
pthread_mutex_init(&mutex_,NULL);
pthread_cond_init(&condition_,NULL);
threads_ = new pthread_t[threadNum_];
//創(chuàng)建threadNum_個(gè)線程,并開始運(yùn)行線程,在線程里取任務(wù)
//線程函數(shù)的參數(shù)是threadpool對(duì)象,每個(gè)線程的參數(shù)對(duì)象都是一樣的(對(duì)象地址一樣),傳對(duì)象是因?yàn)榫€程函數(shù)是static的
for(int i = 0;i < threadNum_;++i)
pthread_create(&threads_[i],NULL,threadFunc,this);
return 0;
}
size_t ThreadPool:: addTask(Task* task)//任務(wù)隊(duì)列中裝的是任務(wù)對(duì)象指針
{
pthread_mutex_lock(&mutex_);
taskDeque_.push_back(task);
size_t size = taskDeque_.size();
pthread_cond_signal(&condition_);
pthread_mutex_unlock(&mutex_);
return size;
}
void ThreadPool::stop()
{
if(!isRunning_)
return;
isRunning_ = false;
pthread_cond_broadcast(&condition_);//激活全部線程的條件變量,先激活首先獲得互斥鎖的那一個(gè)。
for(int i = 0;i < threadNum_;++i)
pthread_join(threads_[i],NULL);//調(diào)用這個(gè)函數(shù)等待一個(gè)線程終止(在主線程中寫時(shí),若新開的線程沒有終止,則阻塞在這里)
//這個(gè)函數(shù)類似于多進(jìn)程中的waitpid(殺死進(jìn)程,防止進(jìn)程僵死)。
delete[] threads_;//指向線程ID的指針
threads_ = NULL;
pthread_mutex_destroy(&mutex_);
pthread_cond_destroy(&condition_);
}
int ThreadPool::size()
{
pthread_mutex_lock(&mutex_);
size_t size = taskDeque_.size();
pthread_mutex_unlock(&mutex_);
return size;
}
Task* ThreadPool::take()//從任務(wù)隊(duì)列中取任務(wù)(取得的是一個(gè)指向任務(wù)對(duì)象的指針)
{
Task* task = NULL;
while(!task)
{
pthread_mutex_lock(&mutex_);
while(taskDeque_.empty() && isRunning_)//沒有任務(wù)的話等待(使用while是防止虛假喚醒)
pthread_cond_wait(&condition_,&mutex_);//線程池stop的時(shí)候這里會(huì)被激活,AND isRunning_ = false
if(!isRunning_)
{
pthread_mutex_unlock(&mutex_);
break;
}
else if(taskDeque_.empty())//防止虛假喚醒需要在喚醒后再做一次判斷。
{
pthread_mutex_unlock(&mutex_);
continue;
}
assert(!taskDeque_.empty());
task = taskDeque_.front();
taskDeque_.pop_front();
pthread_mutex_unlock(&mutex_);
}
return task;
}
void* ThreadPool::threadFunc(void* arg)//在pthread_create之后就會(huì)執(zhí)行,然后從任務(wù)隊(duì)列中取任務(wù),沒有任務(wù)的話等待
{
pthread_t tid = pthread_self();
//static函數(shù)沒有this指針,所以必須傳進(jìn)來對(duì)象,每個(gè)線程中的對(duì)象地址是相同的,也就是說每個(gè)線程中其實(shí)是一個(gè)對(duì)象
ThreadPool* pool = static_cast<ThreadPool*>(arg);
//cout<<pool<<endl;
while (pool->isRunning_)//當(dāng)前線程執(zhí)行完任務(wù)之后,再?gòu)娜蝿?wù)隊(duì)列中取任務(wù)
{
Task* task = pool->take();//如果線程池一直在運(yùn)行,且沒有任務(wù),則會(huì)等待任務(wù)進(jìn)隊(duì)列
if (!task)//
{
printf("thread %lu will exit\n", tid);//執(zhí)行stop函數(shù)之后執(zhí)行(直接調(diào)用stop或者析構(gòu)函數(shù)執(zhí)行),
//因?yàn)槿绻€程池一直在運(yùn)行,且沒有任務(wù),則會(huì)等待任務(wù)進(jìn)隊(duì)列
break;
}
assert(task);
task->run();
}
return 0;
}
}
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include "threadpool.h"
class MyTask: public Z1::Task
{
public:
MyTask(){}
virtual int run()
{
printf("thread[%lu] : %s\n", pthread_self(), (char*)this->arg_);
sleep(1);
return 0;
}
};
int main()
{
char szTmp[] = "hello world";
MyTask taskObj;
taskObj.setArg((void*)szTmp);
Z1::ThreadPool threadPool(10);
for(int i = 0; i < 30; i++)
{
threadPool.addTask(&taskObj);
}
while(1)
{
printf("there are still %d tasks need to process\n", threadPool.size());
if (threadPool.size() == 0)
{
threadPool.stop();
printf("Now I will exit from main\n");
exit(0);
}
sleep(2);
}
sleep(5);
return 0;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。