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;
}```

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章