C++线程池

线程池

#include <vector>
#include <mutex>
#include <thread>
#include <functional>
#include <queue>
#include <atomic>
#include <condition_variable>
#include <iostream>



/**
 * @brief 
线程池实现思路
    定义线程池 std::vectorstd::thread _threads;
    添加线程运行_threads.emplace_back(std::thread(&thread_pool::work, this));
        在work中使用std::unique_lockstd::mutex lock(_mutex); 
        在work中使用条件变量 std::condition_variable _cond;
        在work中 _cond.wait(lock);   wait操作会释放锁,并挂起当前线程 所以会继续下一个线程
    添加任务 append_task 
        会调用  _tasks.push(t);(function 与 bind 结合实现延迟调用)
        _cond.notify_one(); 会释放一个线程
 * 
 */
class thread_pool
{
private:
    using task = std::function<void()>;

    // 定义原子变量
    std::atomic_bool _is_running; //显示线程池的状态

    //定义线程锁 (可改进)
    std::mutex _mutex;
    std::mutex m_mutex;	//互斥量

    //条件变量
    std::condition_variable _cond;
    size_t _thread_no;

    //定义线程池
    std::vector<std::thread> _threads;

    //创建任务
    std::queue<task> _tasks;

public:
    
    //禁止赋值构造
    thread_pool(const thread_pool &tp) = delete;
    thread_pool &operator=(const thread_pool &tp) = delete;

public:
   
    // 定义构造函数
    thread_pool(size_t no)
        : _thread_no(no),
          _is_running(false)
    {
    }

    //西构函数
    ~thread_pool()
    {
        if (_is_running)
            stop();
    }

private:

    //工作区
    void work()
    {
        std::cout << "thread " << std::this_thread::get_id() << " begin to work!" << std::endl;
        while(_is_running)
        {
            //定义的函数相关
            task t;
            {
                //定义一个线程锁
                std::unique_lock<std::mutex> lock(_mutex);
                //std::lock_guard<std::mutex> mylockguard(m_mutex);


                 //不为空
                if(!_tasks.empty())
                {
                    t = _tasks.front();
                    _tasks.pop();
                }
                else if(_is_running && _tasks.empty())
                {
                    //10个线程之后  会在此处进行等待  调用notify_one(); 则结束等待

                    std::cout<<" 等待  _cond.wait "<<std::endl;
                    std::this_thread::sleep_for(std::chrono::milliseconds(5000));

                   // wait操作会释放锁,并挂起当前线程 所以会继续下一个线程
                    _cond.wait(lock);
                   
                }
            }
            
            std::cout<<" 为空 t = "<<std::endl;
            if(t)
            {
                std::cout<<" 执行 t = "<<std::endl;
                //执行线程需要执行的内容
                t();
            }
        }

        std::cout << "thread " << std::this_thread::get_id() << " going to die!" << std::endl;
    }

public:

    //开始
    void start()
    {
        this->_is_running = true;
        for (size_t i = 0; i < _thread_no; i++)
        {
            //开始运行10个线程  结合锁将状态锁住  然后再使用function 进行传入延迟执行程序
            _threads.emplace_back(std::thread(&thread_pool::work, this));
        }
    }
    
    //结束
    void stop()
    {
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _is_running = false;
            _cond.notify_all();   // 唤醒所有线程
        }

        for (std::thread &thd : _threads)
        {
            if (thd.joinable())
            {
                thd.join();
            }
        }
    }

    void append_task(const task &t)
    {
        if (_is_running)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _tasks.push(t);
            _cond.notify_one();
        }
    }
};

void func1()
{
    std::cout << "$thread working in func1 in thread " << std::this_thread::get_id() << std::endl;
}

void func2(int n)
{
    std::cout << "#thread working in func2 in thread " << std::this_thread::get_id() << ";n is " << n << std::endl;
}

void thread_pool_test()
{
    thread_pool pool(2);

    
    //线程已经启动 在等待任务执行
    pool.start();
    std::this_thread::sleep_for(std::chrono::milliseconds(500));

    for (int i = 0; i < 2; i++)
    {
        //通过 function 函数进行延迟运行
        pool.append_task(std::bind(func2, i));
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }

    pool.stop();
}
int main()
{
    thread_pool_test();
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值