多线程-----线程池


线程池

线程的池子,有很多线程,但是数量不会超过池子的限制。-----需要用到多执行流进行任务处理的时候,就从池子中取出一个线程去处理。
应用场景:有大量的数据处理请求,需要多执行流并发/并行处理
若是一个数据请求的到来伴随一个线程的创建去处理,则会产生一些风险以及不必要的消耗:
1.线程若不限制数量的创建,在峰值压力下,线程创建过多,资源耗尽,有程序崩溃的风险
2.处理一个任务的时间:创建线程时间t1+任务处理时间t2+线程销毁时间t3=T,若t2/T比例占据不高,表示大量的资源用于线程的创建与销毁成本上,因此线程池使用已经创建好的线程进行循环任务处理,就避免了大量线程的频繁创建与销毁的时间成本。

自主编写一个线程池:大量线程(每个线程中都是进行循环的任务处理)+任务缓冲队列

在这里插入图片描述
任务队列中的任务,不仅仅是数据,而是包含任务处理方法在内的数据,这时候,线程池中的线程只需要使用传入的方法,处理传入的数据即可,不需要关心是什么数据-------提高了线程池的灵活性

threadpool.hpp

#include <cstdio>
#include <iostream>
#include <queue>
#include <stdlib.h>
#include <pthread.h>

typedef void (*handler_t)(int);
class ThreadTask
{
    public:
        ThreadTask(){
        }
        void SetTask(int data, handler_t handler) {
            _data = data;
            _handler = handler;
        }
        void Run() {//外部只需要调用Run,不需要关系任务如何处理
            return _handler(_data);
        }
    private:
        int _data;//任务中要处理的数据
        handler_t _handler;//任务中处理数据的方法
};

#define MAX_THREAD 5
class ThreadPool
{
    public:
        ThreadPool(int max_thr = MAX_THREAD):_thr_max(max_thr){
            pthread_mutex_init(&_mutex, NULL);
            pthread_cond_init(&_cond, NULL);
            for (int i = 0; i < _thr_max; i++) {
                pthread_t tid;
                int ret = pthread_create(&tid, NULL, thr_start, this);
                if (ret != 0) {
                    printf("thread create error\n");
                    exit(-1);
                }
            }
        }
        ~ThreadPool(){
            pthread_mutex_destroy(&_mutex);
            pthread_cond_destroy(&_cond);
        }
        bool TaskPush(ThreadTask &task) {
            pthread_mutex_lock(&_mutex);
            _queue.push(task);
            pthread_mutex_unlock(&_mutex);
            pthread_cond_broadcast(&_cond);//如对后唤醒所有线程,谁抢到谁处理
            return true;
        }
        // 类的成员函数,有一个隐藏的默认参数,是this指针
        // 线程入口函数,没有this指针,如何操作私有成员呢??
        static void *thr_start(void *arg) {
            ThreadPool *p = (ThreadPool *) arg;
            //不断的从任务队列中取出任务,执行任务的Run接口就可以
            //每一个任务节点中包含了要处理的数据,以及如何处理的函数
            while(1) {
                pthread_mutex_lock(&p->_mutex);
                while(p->_queue.empty()) {
                    pthread_cond_wait(&p->_cond, &p->_mutex);
                }
                ThreadTask task;
                task = p->_queue.front();
                p->_queue.pop();
                pthread_mutex_unlock(&p->_mutex);
                task.Run();//任务的处理要放在解锁之外,因为当前的所保护的时队列的操作
            }
            return NULL;
        }
    private:
        int _thr_max; // 线程池中线程的最大数量--根据这个初始化创建指定数量的线程
        std::queue<ThreadTask> _queue;
        pthread_mutex_t _mutex;//保护队列操作的互斥锁
        pthread_cond_t _cond;//实现从队列中获取节点的同步条件变量
};

main.cpp

#include <unistd.h>
#include "threadpool.hpp"

void test_func(int data)
{
    int sec = (data % 3) + 1;
    printf("tid:%p -- get data:%d , sleep:%d\n", pthread_self(), data, sec);
    sleep(sec);
}
void tmp_func(int data) {
    printf("tid:%p -- tmp_func\n", pthread_self());
    sleep(1);
}
int main()
{
    ThreadPool pool;
    for(int i = 0; i < 10; i++) {
        ThreadTask task;
        if (i % 2 == 0) {
            task.SetTask(i, test_func);
        }else {
            task.SetTask(i, tmp_func);
        }
        pool.TaskPush(task);
    }

    sleep(1000);
    return 0;
}

在这里插入图片描述

总结

要处理什么数据,如何处理的方法,组织成为一个任务节点,交给线程池,线程池中找出任意一个线程只需要使用方法处理数据即可。
STL中的容器是线程安全的吗?-----不是
智能指针式线程安全的吗?----unique_ptr局部操作/shared_ptr原子操作,不涉及线程安全的问题

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值