领导者/追随者模式,具体来说,设计一种线程池机制,每次只让一个线程(领导者)等待队列不空,其他线程(追随者)排队成为领导者。从队列中取到任务后,当前领导者首先将一个追随者线程提拔为新的领导者线程,再扮演处理线程角色。当前领导者线程等待队列的元素入队时,可能有多个处理线程同时处理任务。处理完任务后,处理线程再次番禺追随者线程的角色,等待再次成为领导者线程。
要将追随者线程提拔为领导者线程以及判断当前哪个线程为领导者线程,有多种实现方式:
1、LIFO顺序:在很多应用中,哪个追随线程提拔为领导者线程都无关紧要。在这种情况下,可以后进先出的方式提拔追随者线程为领导者线程。以这种方式可以最大限度地提高CPU的缓存亲和性。如果最近诸事的线程重新运行时,执行的代码和数据几乎相同,将因缓存亲和性而改善系统性能。然而,要实现LIFO提拔协议,需要一个额外的数据结构(如实现一个等待线程栈,通过信号(或其他方式)唤醒最近入栈的线程,提拔为领导者线程),而不能仅仅使用原生的操作系统同步对象(如信号量)。
2、优先级顺序:在有些应用程序中,线程的优先级可能不一样,在这种情况下,可能必须根据优先级来提拔追随者线程。可以使用优先级队列,在提拔线程时,取出优先级最高的线程id,通过信号(或其他方式)唤醒线程,提拔为领导者线程。
3、实现定义的顺序:使用操作系统同步器(如信号量或条件变量)来提拔追随者线程,这种排序方式最常见,操作系统同步器通常以实现定义的顺序分派等待的线程。这种协议的优点在于,直接对应于原生操作系统同步器。
本文将用c++实现第三种方式的线程池。
首先来看一个简单队列的实现,这个队列是适用于单进单出的无锁队列,如果要用在多线程可以变形成双锁队列,本文的线程池就是用的双锁队列,适用于多线程的无锁Disruptor队列实现稍微复杂点,这个将在后面实现。
#pragma once#include <stdint.h>#include <vector>using std::vector;template <class T>class SimpleQueue{public:SimpleQueue(uint32_t nSize=4096){SetMaxSize(nSize);m_nInPos=0;m_nOutPos=0;}~SimpleQueue(){}bool Put(T &in){if(m_nInPos-m_nOutPos>=m_nMaxSize){return false;}uint32_t nPos=m_nInPos&m_nMaxSizeLess;m_vDataBuffer[nPos]=in;++m_nInPos;return true;}bool Fetch(T& out){if(m_nInPos-m_nOutPos==0){return false;}uint32_t nPos=m_nOutPos&m_nMaxSizeLess;out=m_vDataBuffer[nPos];++m_nOutPos;return true;}void SetMaxSize(uint32_t nMaxSize){m_nMaxSize=1;while(nMaxSize>>=1){m_nMaxSize<<=1;}m_nMaxSizeLess=m_nMaxSize-1;m_vDataBuffer.resize(m_nMaxSize);}uint32_t MaxSize(){return m_nMaxSize;}uint32_t Size(){return m_nInPos-m_nOutPos;}private:volatile uint32_t m_nInPos;volatile uint32_t m_nOutPos;uint32_t m_nMaxSize;uint32_t m_nMaxSizeLess;vector<T> m_vDataBuffer;};
接下来是Leader/Follower线程池的实现,先看ThreadPool.h头文件
#pragma once#include <pthread.h>#include <stdio.h>#include "SimpleQueue.h"const int NO_CURRENT_LEADER=0;struct Job{void *arg;void *(*process)(void *arg);};class ThreadPool{public:ThreadPool(uint32_t nQueueSize=4096,uint32_t nThreadNum=8);~ThreadPool();bool AddWorker(void *(*process)(void *arg),void* arg);void Destroy();private:static void * WorkProcess(void *arg);void JoinFollower();void PromoteNewLeader();SimpleQueue<Job*> m_oQueue;pthread_cond_t m_pQueueNotEmpty;pthread_cond_t m_pQueueNotFull;pthread_cond_t m_pQueueEmpty;pthread_cond_t m_pNoLeader;pthread_mutex_t m_pLeaderMutex;pthread_mutex_t m_pQueueHeadMutex;pthread_mutex_t m_pQueueTailMutex;bool m_bQueueClose;bool m_bPoolClose;pthread_t *m_vThreadID;pthread_t m_oLeaderID;uint32_t m_nThreadNum;uint32_t m_nMaxTaskNum;};
然后是ThreadPool.cpp的实现
#include "ThreadPool.h"using namespace std;ThreadPool::ThreadPool(uint32_t nQueueSize,uint32_t nThreadNum):m_oQueue(nQueueSize),m_oLeaderID(NO_CURRENT_LEADER){m_nThreadNum=nThreadNum;m_bQueueClose=false;m_bPoolClose=false;m_nMaxTaskNum=m_oQueue.MaxSize();pthread_cond_init(&m_pQueueNotEmpty,NULL);pthread_cond_init(&m_pQueueNotFull,NULL);pthread_cond_init(&m_pQueueEmpty,NULL);pthread_cond_init(&m_pNoLeader,NULL);pthread_mutex_init(&m_pLeaderMutex,NULL);pthread_mutex_init(&m_pQueueHeadMutex,NULL);pthread_mutex_init(&m_pQueueTailMutex,NULL);pthread_attr_t attr;pthread_attr_init (&attr);pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);m_vThreadID=new pthread_t[m_nThreadNum];for(size_t i=0;i<nThreadNum;++i){pthread_create(&(m_vThreadID[i]),&attr,WorkProcess,this);}}ThreadPool::~ThreadPool(){Destroy();pthread_cond_destroy(&m_pQueueNotEmpty);pthread_cond_destroy(&m_pQueueNotFull);pthread_cond_destroy(&m_pQueueEmpty);pthread_cond_destroy(&m_pNoLeader);pthread_mutex_destroy(&m_pQueueHeadMutex);pthread_mutex_destroy(&m_pQueueTailMutex);pthread_mutex_destroy(&m_pLeaderMutex);}void ThreadPool::Destroy(){if (m_bPoolClose)return;//关闭队列,不在接受新的任务m_bQueueClose=1;pthread_mutex_lock(&m_pQueueTailMutex);while (m_oQueue.Size()!=0){pthread_cond_wait(&(m_pQueueEmpty), &(m_pQueueTailMutex));}m_bPoolClose=1;pthread_mutex_unlock(&m_pQueueTailMutex);//唤醒所有线程,准备退出pthread_cond_broadcast(&m_pNoLeader);pthread_cond_broadcast(&m_pQueueNotEmpty);delete [] m_vThreadID;}bool ThreadPool::AddWorker(void *(*process)(void *arg),void* arg){if(m_bQueueClose)return false;Job *pNewJob=new Job;pNewJob->arg=arg;pNewJob->process=process;pthread_mutex_lock(&m_pQueueHeadMutex);while(m_oQueue.Size()>=m_nMaxTaskNum&&!m_bQueueClose){pthread_cond_wait(&m_pQueueNotFull, &m_pQueueHeadMutex);}if(m_bQueueClose){delete pNewJob;pthread_mutex_unlock(&m_pQueueHeadMutex);return false;}m_oQueue.Put(pNewJob);pthread_mutex_unlock(&m_pQueueHeadMutex);pthread_cond_signal(&m_pQueueNotEmpty);return true;}void * ThreadPool::WorkProcess(void *arg){ThreadPool *pThreadPool=(ThreadPool*)arg;pThreadPool->JoinFollower();while(true){pthread_mutex_lock(&(pThreadPool->m_pQueueTailMutex));while(pThreadPool->m_oQueue.Size()==0&&!pThreadPool->m_bPoolClose){pthread_cond_wait(&(pThreadPool->m_pQueueNotEmpty),&(pThreadPool->m_pQueueTailMutex));}pthread_mutex_unlock(&(pThreadPool->m_pQueueTailMutex));if(pThreadPool->m_bPoolClose){pthread_exit(NULL);}Job *pJob;pThreadPool->m_oQueue.Fetch(pJob);if(pThreadPool->m_bQueueClose&&pThreadPool->m_oQueue.Size()==0){pthread_cond_signal(&(pThreadPool->m_pQueueEmpty));}pthread_cond_signal(&(pThreadPool->m_pQueueNotFull));pThreadPool->PromoteNewLeader();pJob->process(pJob->arg);delete pJob;pThreadPool->JoinFollower();}return NULL;}void ThreadPool::JoinFollower(){pthread_mutex_lock(&m_pLeaderMutex);while(m_oLeaderID!=NO_CURRENT_LEADER&&!m_bPoolClose){pthread_cond_wait(&m_pNoLeader,&m_pLeaderMutex);}if(m_bPoolClose){pthread_mutex_unlock(&m_pLeaderMutex);pthread_exit(NULL);}m_oLeaderID=pthread_self();pthread_mutex_unlock(&m_pLeaderMutex);}void ThreadPool::PromoteNewLeader(){m_oLeaderID=NO_CURRENT_LEADER;pthread_cond_signal(&m_pNoLeader);}
以上就是领导者/追随者线程池的实现,下一节将结合这个线程池实现一个简单的epoll模型。