C++ 並沒有提供 ThreadPool 的實作,但 boost 有實作(請看參考[1]),Github 上找到一個簡單用C++11 std::thread 時做出 ThreadPool 的例子,如下︰ C++11 ThreadPool A simple C++11 Thread Pool implementation https://github.com/progschj/ThreadPool ThreadPool.h Step 1. 透過 ThreadPool::ThreadPool() 建構子後,裡面會建立執行緒(workers.emplace_back)並放入執行緒池,並且等待事件通知(condition_variable) Step 2. 透過 ThreadPool::enqueue() 放入 task 的函式後會去通知(condition.notify_one)該開始執行了 Step 3. 收到通知(condition.wait)後就開始執行該task 用法:將你的 task 函式放進去,不用自己建立執行緒。 其他值得學習的地方:std::forward 用法 與 std::future 用法 參考 [1] boost::threadpool https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/thread_pool.html [2] 基於C++11的線程池(threadpool),簡潔且可以帶任意多的參數 https://www.cnblogs.com/lzpong/p/6397997.html [3] c++ thread pool 使用解析 https://blog.csdn.net/carbon06/article/details/78171588
留言
張貼留言