此文与《linux高性能服务器编程》—— 一种高效的异步进程池的实现 是姊妹篇。
(1)线程池框架
(2)源代码及注释
#ifndef THREADPOOL
#define THREADPOOL
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <pthread.h>
#include <set>
class thread //工作线程类
{
public:
pthread_t tid; //线程标识
int pipefd[2]; //与主线程通信的管道
};
template <typename T> //T是客户类
class threadpool //线程池类
{
private:
static const int MAX_THREAD_NUMBER = 16; //工作线程的最大数量
static const int USER_PER_THREAD = 1000; //每个工作线程负责的客户的最大数量
static const int MAX_EVENT_NUMBER = 1000; //epoll内核事件表所能容纳的事件的最大数量
int thread_number; //工作线程的实际数量
int listenfd; //指向监听socket的fd,主/工作线程共用同一个
thread* work_thread; //管理各工作线程的信息
static threadpool* instance; //指向此类的唯一对象
private:
threadpool(int _listenfd, int _thread_number = 8);
static void* worker(void* arg); //工作线程的执行函数
public:
static threadpool* create(int listenfd, int thread_number = 8)
//返回此线程池类的唯一对象
{
if(!instance)
instance = new threadpool(listenfd, thread_number);
return instance;
}
static threadpool* get_instance()
{
return instance;
}
~threadpool()
{
delete[] work_thread;
}
void run(); //执行主线程的任务
};
template <typename T>
threadpool<T>* threadpool<T>::instance = NULL;
int sig_pipefd[2]; //信号管道,主/工作线程都需要
int setnonblocking(int fd) //将fd设为非阻塞
{
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
void addfd(int epollfd, int fd, std::set<int> &used_fd)
//将fd的读事件插