C++11实现线程池

    xiaoxiao2023-10-16  35

    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)