《linux高性能服务器编程》—— 一种高效的异步线程池的实现

此文与《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的读事件插
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值