Boost threadpool、thread_group、c ++ 11スレッドプールの例
Boost Threadpool Thread_group
ここでは、ブースト2スレッドプールとC + +11実装スレッドプールの使用法を紹介します。
主な手順は次のとおりです。
スレッドプールで提供されるサービススレッドの数を設定します
int threads = thread::hardware_concurrency()
各スレッドは無限ループを実行し、新しいタスクが無限ループに到着するのを待って、タスクを実行する必要があります
vector pool for (int i = 0 i 無限ループ関数
while(true) { { unique_lock lock(queue_mutex) condition.wait(lock,[]{return !Queue.empty()}) Task = Queue.front() Queue.pop() } Task() }
タスクをタスクキューに追加する
void enqueue(function new_task) { { unique_lock lock(queue_mutex) Queue.push(new_task) } condition.notify_one() } class ThreadPool { public: ThreadPool(size_t threads) : stop(false) { for(size_t i = 0iqueue_mutex) this->condition.wait(lock, [this]) if(this->stop && this->tasks.empty()) return task = std::move(this->tasks.front()) this->tasks.pop() } task() } } ) } // add new work item to the pool void enqueue(std::function& task) { { std::unique_lock lock(queue_mutex) // don't allow enqueueing after stopping the pool if(stop) throw std::runtime_error('enqueue on stopped ThreadPool') tasks.emplace(task) } condition.notify_one() } ~ThreadPool() { { std::unique_lock lock(queue_mutex) stop = true } condition.notify_all() for(std::thread &worker: workers) worker.join() } private: std::vector workers // the task queue std::queue tasks // synchronization std::mutex queue_mutex std::condition_variable condition bool stop }
参照
https://www.codeproject.com/Articles/664709/Creating-a-Work-Queue-Thread-Pool-Application-Usin
https://ce39906.github.io/2018/03/29/C-Thread-Pool-%E4%BD%BF%E7%94%A8%E8%A7%A3%E6%9E%90/