gcc 5.4 编译通用 C++ 线程池实现

本文展示了如何使用GCC 5.4在Linux(CentOS 7)环境下编译一个通用的C++11线程池。通过示例代码详细解释了线程池的初始化、添加任务、等待任务完成以及停止线程池的过程,支持全局函数、类成员函数以及lambda表达式。
摘要由CSDN通过智能技术生成




//todo
/*
[root@Slave02 thread]# g++ thread_pool.cpp  -o thread_pool -g -Wall -std=gnu++11 -lpthread;./thread_pool
Hello ThreadPool
class Test2 Hello world,0
Current thread id: 140287557768960, global function test_task str: Hello world
class Test Hello world,0
第一批 4 个任务完成,wait_limit_task exit
class Test Hello world,1
class Test Hello world,0
class Test Hello world,2
第二批 3 个任务完成,wait_limit_task exit
class Test2 Hello world,2
class Test2 Hello world,3
class Test2 Hello world,4
class Test2 Hello world,5
class Test2 Hello world,0
class Test2 Hello world,1
第三批 6 个任务完成,wait_limit_task exit
##############END#################
*/




#ifndef _THREAD_POOL_INCLUDE_H
#define _THREAD_POOL_INCLUDE_H


#include <cassert>
#include <cstdint>
#include <iostream>
#include <sstream>
#include <vector>
#include <queue>
#include <string>
#include <algorithm>
#include <functional>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <type_traits>


using namespace std;


class CThread_Pool
{
private:
    using work_thread_ptr_t = std::shared_ptr<std::thread>;
    using task_t = std::function<void ()>;
public:
    ~CThread_Pool()
    {
        stop();
    }


    //初始化指定线程池内线程数
    void init_thread_num(uint32_t num)
    {
        is_stop_threadpool_.store(false);
        limit_task_num_.store(0);
        if (num <= 0 || num > MAX_THREAD_SIZE)
        {
            std::string str = "Number of threads in the range of 1 to " + std::to_string(MAX_THREAD_SIZE);
            throw std::invalid_argument(str);
        }


        for (uint32_t i = 0; i < num; ++i)
        {
            work_thread_ptr_t t = std::make_shared<std::thread>(std::bind(&CThread_Pool::run_task, this));
            thread_vec_.emplace_back(t);
        }
    }
    
    //等待指定执行的任务结束
    void wait_limit_task()
    {
        // 线程池循环取任务
        std::unique_lock<std::mutex> locker(limit_task_);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值