C++11实现线程池

threadgroup.h

#include <thread>
#include <unordered_map>

using namespace std;

class thread_group{
private:
    thread_group(thread_group const&);
    thread_group& operator=(thread_group const&);
public:
    thread_group(){}
    ~thread_group(){
        _threads.clear();
    }

    template<typename F>
    thread* create_thread(F &&threadfunc){
        /*
        make_shared<T>(args)返回一个shared_ptr,指向一个动态分配的类型为T的对象。使用args初始化此对象
        */
        auto thread_new = std::make_shared<thread>(threadfunc);
        _thread_id = thread_new->get_id();
        _threads[_thread_id] = thread_new;
        return thread_new.get();
    }
    
    void remove_thread(thread* thrd){
        auto it = _threads.find(thrd->get_id());
        if(it != _threads.end()){
            _threads.erase(it);
        }
    }

    size_t size(){
        return _threads.size();
    }

    void join_all(){
        if(is_this_thread_in()){
            throw runtime_error("thread_group:trying joining itself");
        }
        for(auto &it : _threads){
            if(it.second->joinable()){
                it.second->join();
            }
        }
        _threads.clear();
    }

    bool is_this_thread_in(){
        auto thread_id = this_thread::get_id();
        return _threads.find(thread_id) != _threads.end();
    }
private:
    unordered_map<thread::id, std::shared_ptr<thread>> _threads;
    thread::id _thread_id;
};

简单测试

#include "threadgroup.h"
#include <iostream>
#include <thread>

void do_some_work(){
    std::cout<<"this thread is " <<std::this_thread::get_id()<<std::endl;
}

int main(){
    thread_group test_group;
    // for(int i = 0; i < std::thread::hardware_concurrency(); i++)
    //     test_group.create_thread(do_some_work);

    for(int i = 0; i < 100; i++)
        test_group.create_thread(do_some_work);
    test_group.join_all();
    return 0;
}```

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值