现代c++线程池

Tifa-Best / 2025-01-20 / 原文

#include <condition_variable>
#include <deque>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
using namespace std;

using closure = function<void(void)>;

class ThreadPool {
  mutex mtx_;
  condition_variable cv_;
  bool running_;
  uint thread_count_;

  deque<closure> task_queue_;
  vector<thread> worker_pool_;

 public:
  ThreadPool(uint thread_count) : thread_count_(thread_count), running_(true) {
    for (uint i = 0; i < thread_count; i++) {
      auto worker = [&](void) {
        while (true) {
          unique_lock<mutex> lk(mtx_);
          cv_.wait(lk,
                   [&](void) { return (!task_queue_.empty()) || (!running_); });

          if (!running_) break;

          auto task = task_queue_.front();
          task_queue_.pop_front();
          lk.unlock();

          task();
        }
      };
      worker_pool_.emplace_back(worker);
    }
  }

  void push_back(closure c) {
    lock_guard<mutex> lk(mtx_);
    task_queue_.push_back(c);
    cv_.notify_one();
  }

  ~ThreadPool() {
    running_ = false;
    cv_.notify_all();
    for (auto &it : worker_pool_) it.join();
  }
};

int main(int argc, char const *argv[]) {
  ThreadPool pool(4);

  for (int i = 0; i < 100; i++)
    pool.push_back([=](void) { cout << i << endl; });
  this_thread::sleep_for(10ms);

  return 0;
}