线程池及其实现相关浅析

线程池是什么

线程池也是池化技术的一种应用。与异步响应池连接池内存池等一样,主要是为了控制资源并且将资源创建和销毁的性能损耗尽可能的规避掉。
放到线程池这个概念上,线程池就是将线程资源预先储存到线程池实例中,之后我们需要线程执行任务时,仅仅需要将任务甩给线程池,主动地去使用线程资源完成任务。

线程池的作用&意义(为什么需要线程池)

某项任务非常耗时,影响了进程模块的整体性能表现。如reactor模型中(单线程网络IO模型),整体的时间损耗可以看做两部分:

  1. 响应网络请求
  2. 进行业务处理

如果业务处理比较复杂,那么每一次事件响应过程都需要等业务处理完毕后再进行下一次响应,就会影响整体的表现,让我们感觉用起来很卡。这种情况下,进程模块会随着业务的复杂度而变得愈发臃肿低效。比较好的方法是将网络响应功能模块业务处理模块剥离开,网络响应模块只负责响应网络请求。业务处理模块交给线程池去处理,组成一个简单的生产消费模型,线程池在这种场景下提供了以下功能:

  1. 实现了响应和解析的异步处理,缓解耗时业务带来的压力
  2. 更好的利用了多核处理器的多核优势,更好的复用线程资源
  3. 可以很好的控制线程资源的占用

线程池的典型应用

在传统的C/S服务框架中,服务器对于客户端的响应大致分为以下五个部分

  • read(接收处理数据)
  • decode(解析协议获取需求)
  • compute(进行需求的实现,即业务处理过程)
  • decode(将处理结果重组协议)
  • send(返回处理后的数据)
  1. NGINX中使用线程池处理文件缓冲(优化compute)
    在这里插入图片描述

  2. redis中使用线程池进行数据包解析和压缩(优化read,encode,decode,send)
    在这里插入图片描述

  3. skynet使用线程池优化整体处理
    在这里插入图片描述

怎样实现线程池

基本思路

线程池基本上就是一个生产消费模型,主要由以下几部分构成:

  1. 生产者线程-发布任务,任务简单,通常为一个
  2. 队列:缓存任务,为二个线程组的异步提供内存资源
  3. 消费者线程:消费任务,也是线程池的主体,通常为多个

注:消费者线程的线程数设置有以下经验公式:

  1. IO密集型任务,线程数设置一般为2*核心数 + 2
  2. CPU密集型任务,线程数一般设置为核心数

接口设计

  1. 创建线程池(线程数量,任务队列长度)
  2. 销毁线程池(标记线程退出,通知所有线程)
  3. 生产者抛出任务(构造任务,放入队列,通知线程)

posix线程池大致实现

基本定义

/**任务node*/
typedef struct task_t {
    handler_pt func;	///< 线程执行的注册回调
    void * arg;			///< 用户数据
} task_t;

/*任务队列*/
typedef struct task_queue_t {
    uint32_t head;	///< 头下标,
    uint32_t tail;	///< 尾下标,与头下标详解构成队列容量,ring buffer的思想
    uint32_t count; ///< 任务计数
    task_t *queue;
} task_queue_t;

/*线程池实例*/
struct thread_pool_t {
    pthread_mutex_t mutex;		///< 互斥锁,用于资源保护
    pthread_cond_t condition;	///< 条件变量,用于同步
    pthread_t *threads;			
    task_queue_t task_queue;

    int closed;
    int started; // 当前运行的线程数

    int thrd_count;
    int queue_size;
};

基本接口定义


/*申请线程和内存资源,初始化*/
thread_pool_t *
thread_pool_create(int thrd_count, int queue_size) {
    thread_pool_t *pool;

    if (thrd_count <= 0 || queue_size <= 0) {
        return NULL;
    }

    pool = (thread_pool_t*) malloc(sizeof(*pool));
    if (pool == NULL) {
        return NULL;
    }

    pool->thrd_count = 0;
    pool->queue_size = queue_size;
    pool->task_queue.head = 0;
    pool->task_queue.tail = 0;
    pool->task_queue.count = 0;

    pool->started = pool->closed = 0;

    pool->task_queue.queue = (task_t*)malloc(sizeof(task_t)*queue_size);
    if (pool->task_queue.queue == NULL) {
        // TODO: free pool
        return NULL;
    }

    pool->threads = (pthread_t*) malloc(sizeof(pthread_t) * thrd_count);
    if (pool->threads == NULL) {
        // TODO: free pool
        return NULL;
    }

    int i = 0;
    for (; i < thrd_count; i++) {
        if (pthread_create(&(pool->threads[i]), NULL, thread_worker, (void*)pool) != 0) {
            // TODO: free pool
            return NULL;
        }
        pool->thrd_count++;
        pool->started++;
    }
    return pool;
}
/*发布任务*/
int
thread_pool_post(thread_pool_t *pool, handler_pt func, void *arg) {
    if (pool == NULL || func == NULL) {
        return -1;
    }

    task_queue_t *task_queue = &(pool->task_queue);

    if (pthread_mutex_lock(&(pool->mutex)) != 0) {
        return -2;
    }

    if (pool->closed) {
        pthread_mutex_unlock(&(pool->mutex));
        return -3;
    }

    if (task_queue->count == pool->queue_size) {
        pthread_mutex_unlock(&(pool->mutex));
        return -4;
    }

    task_queue->queue[task_queue->tail].func = func;
    task_queue->queue[task_queue->tail].arg = arg;
    task_queue->tail = (task_queue->tail + 1) % pool->queue_size;
    task_queue->count++;
	/*唤醒一个等待线程,老版本可能有惊群问题*/
    if (pthread_cond_signal(&(pool->condition)) != 0) {
        pthread_mutex_unlock(&(pool->mutex));
        return -5;
    }
    pthread_mutex_unlock(&(pool->mutex));
    return 0;
}
/*释放线程池资源*/
static void 
thread_pool_free(thread_pool_t *pool) {
    if (pool == NULL || pool->started > 0) {
        return;
    }

    if (pool->threads) {
        free(pool->threads);
        pool->threads = NULL;

        pthread_mutex_lock(&(pool->mutex));
        pthread_mutex_destroy(&pool->mutex);
        pthread_cond_destroy(&pool->condition);
    }

    if (pool->task_queue.queue) {
        free(pool->task_queue.queue);
        pool->task_queue.queue = NULL;
    }
    free(pool);
}
/*逐个终止线程*/
int
wait_all_done(thread_pool_t *pool) {
    int i, ret=0;
    for (i=0; i < pool->thrd_count; i++) {
        if (pthread_join(pool->threads[i], NULL) != 0) {
            ret=1;
        }
    }
    return ret;

/*销毁线程池*/
int
thread_pool_destroy(thread_pool_t *pool) {
    if (pool == NULL) {
        return -1;
    }

    if (pthread_mutex_lock(&(pool->mutex)) != 0) {
        return -2;
    }

    if (pool->closed) {
        thread_pool_free(pool);
        return -3;
    }

    pool->closed = 1;

    if (pthread_cond_broadcast(&(pool->condition)) != 0 || 
            pthread_mutex_unlock(&(pool->mutex)) != 0) {
        thread_pool_free(pool);
        return -4;
    }

    wait_all_done(pool);

    thread_pool_free(pool);
    return 0;
}
/*线程函数*/
static void *
thread_worker(void *thrd_pool) {
    thread_pool_t *pool = (thread_pool_t*)thrd_pool;
    task_queue_t *que;
    task_t task;
    for (;;) {
        pthread_mutex_lock(&(pool->mutex));
        que = &pool->task_queue;
        // 虚假唤醒   linux  pthread_cond_signal
        // linux 可能被信号唤醒
        // 业务逻辑不严谨,被其他线程抢了该任务
        while (que->count == 0 && pool->closed == 0) {
            // pthread_mutex_unlock(&(pool->mutex))
            // 阻塞在 condition
            // ===================================
            // 解除阻塞
            // pthread_mutex_lock(&(pool->mutex));
            pthread_cond_wait(&(pool->condition), &(pool->mutex));
        }
        if (pool->closed == 1) break;
        task = que->queue[que->head];
        que->head = (que->head + 1) % pool->queue_size;
        que->count--;
        pthread_mutex_unlock(&(pool->mutex));
        (*(task.func))(task.arg);
    }
    pool->started--;
    pthread_mutex_unlock(&(pool->mutex));
    pthread_exit(NULL);
    return NULL;
}

优点

实现简单清晰,基本概括了线程池是怎么回事

弊端

较多的使用了加锁解锁的系统调用,实际上内核维护mutex上下文也废了不少性能,更好的方法是实现无锁队列,之后再填坑。

c/cpp提升

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我叫大魔宝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值