当前位置: 首页 > news >正文

【C/C++】现代C++线程池:从入门到生产级实现

文章目录

  • 现代C++线程池:从入门到生产级实现
    • 🧠 What Is a Thread Pool?
    • 🧩 Why Use a Thread Pool?
    • 🔰 Part 1: Basic Thread Pool (Beginner)
      • 🔧 Minimal Working Code:
      • ✅ Usage:
    • 🧑‍🔬 Part 2: Improving It (Intermediate)
      • 🧵 Add Return Values with `std::future`
    • ⚙️ Part 3: Production-Grade Features (Expert)
      • ✅ Features to Add:
    • 🧵 Part 4: C++20/23 Style Thread Pool
    • 📚 Libraries You Should Know
    • 🧭 Summary

现代C++线程池:从入门到生产级实现

Introduction to thread_pool in modern C++, guiding you through the core ideas and gradually moving toward production-quality implementations. The content is designed to help you deeply understand how thread pools work, and how to write your own using C++17/20/23.


🧠 What Is a Thread Pool?

A thread pool is a collection of pre-spawned threads that wait for tasks to execute. Instead of creating a thread for every task (which is expensive), you reuse a fixed number of threads, each pulling tasks from a task queue.


🧩 Why Use a Thread Pool?

  • ✅ Avoid the overhead of frequent thread creation/destruction.
  • ✅ Reuse a fixed number of threads.
  • ✅ Efficient for high-throughput or I/O-bound systems.
  • ✅ Works well with producer-consumer or event-driven designs.

🔰 Part 1: Basic Thread Pool (Beginner)

A very basic thread pool in C++ using:

  • std::thread
  • std::mutex
  • std::condition_variable
  • std::function
  • std::queue

🔧 Minimal Working Code:

#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>class ThreadPool {
public:ThreadPool(size_t num_threads);~ThreadPool();void enqueue(std::function<void()> task);private:std::vector<std::thread> workers;std::queue<std::function<void()>> tasks;std::mutex queue_mutex;std::condition_variable condition;std::atomic<bool> stop;
};ThreadPool::ThreadPool(size_t num_threads) : stop(false) {for (size_t i = 0; i < num_threads; ++i) {workers.emplace_back([this]() {while (true) {std::function<void()> task;{std::unique_lock<std::mutex> lock(this->queue_mutex);this->condition.wait(lock, [this]() {return this->stop || !this->tasks.empty();});if (this->stop && this->tasks.empty())return;task = std::move(this->tasks.front());this->tasks.pop();}task(); // run the task}});}
}void ThreadPool::enqueue(std::function<void()> task) {{std::lock_guard<std::mutex> lock(queue_mutex);tasks.push(std::move(task));}condition.notify_one();
}ThreadPool::~ThreadPool() {stop = true;condition.notify_all();for (std::thread &worker : workers)worker.join();
}

✅ Usage:

int main() {ThreadPool pool(4);for (int i = 0; i < 10; ++i) {pool.enqueue([i]() {std::cout << "Running task " << i << " on thread " << std::this_thread::get_id() << "\n";});}std::this_thread::sleep_for(std::chrono::seconds(1));return 0;
}

🧑‍🔬 Part 2: Improving It (Intermediate)

🧵 Add Return Values with std::future

Change enqueue() to return a std::future<T> for each task.

template<class F, class... Args>
auto enqueue(F&& f, Args&&... args)-> std::future<typename std::invoke_result_t<F, Args...>> {using return_type = typename std::invoke_result_t<F, Args...>;auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));std::future<return_type> res = task->get_future();{std::lock_guard<std::mutex> lock(queue_mutex);tasks.emplace([task]() { (*task)(); });}condition.notify_one();return res;
}

Now you can write:

auto future = pool.enqueue([]() {return 42;
});
std::cout << "Result: " << future.get() << "\n";

⚙️ Part 3: Production-Grade Features (Expert)

✅ Features to Add:

FeatureDescription
Dynamic thread resizingIncrease/decrease thread count
Task prioritizationUse std::priority_queue
Shutdown optionsGraceful (drain tasks) vs Immediate
Exception handlingCatch exceptions in tasks
Thread affinity / namingSet thread names or pin to cores
Work stealingFor maximum throughput
Thread-local storageUse thread_local for caches
Integration with coroutines (C++20)Schedule coroutines using the pool

🧵 Part 4: C++20/23 Style Thread Pool

For advanced users, consider using:

  • std::jthread (C++20)
  • std::stop_token
  • std::barrier or std::latch
  • Coroutines (co_await, std::suspend_always)
  • execution::scheduler (C++23 proposal)

Example for C++20 cooperative cancellation:

void worker(std::stop_token stop_token) {while (!stop_token.stop_requested()) {// ...}
}std::jthread t(worker); // can be stopped cleanly

📚 Libraries You Should Know

If you prefer using proven libraries:

LibraryLinkNotes
CTPLEasy-to-use thread pool
BS::thread_poolHeader-only, fast
Boost::asioHeavy but feature-rich
libunifexAdvanced async patterns
follyFacebook’s production async primitives

🧭 Summary

LevelKey Concepts
Beginnerstd::thread, mutex, condition variable, basic queue
Intermediatefutures, exception handling, RAII, std::function, shared task management
Expertstd::jthread, coroutines, scheduling policies, custom allocators, task stealing

相关文章:

  • RocketMQ 顺序消息实现原理详解
  • 2.前端汇总
  • 三色光源投影暗战:FSHD 如何撕开 DLP/3LCD 垄断缺口?
  • 计算机科技笔记: 容错计算机设计05 n模冗余系统 双模冗余系统 Duplex Systems
  • AIGC降重工具
  • 逆元(费马,扩展欧几里得)
  • SparkContext介绍
  • Robot Studio开发入门指南
  • Python 数据库编程
  • 进阶知识:自动化框架开发之有参的函数装饰器@wraps()和无参之间的对比
  • Ubuntu软件仓库与更新源配置指南
  • LeetCode 438. 找到字符串中所有字母异位词 | 滑动窗口与字符计数数组解法
  • java 异常验证框架validation,全局异常处理,请求验证
  • Python训练营打卡31
  • 任务分配不均,如何平衡工作负担?
  • Glasgow Smile: 2靶场渗透
  • Java 中 final 与 static 的区别
  • 什么是数据中台
  • JUC编程monitor、锁膨胀以及相关关键字
  • 友思特应用 | LCD显示屏等玻璃行业的OCT检测应用
  • 引入AI Mode聊天机器人,Gemini 2.5 Pro加持,谷歌重塑搜索智能
  • 换灯如换脸!西安碑林整修重开观展体验提升
  • 以色列“全面接管”加沙“雷声大雨点小”:援助政策引内讧,美欧失去耐心
  • 宋鹍已任首都机场集团有限公司董事长、党委书记
  • 重庆一男大学生掉进化粪池死亡,重庆对外经贸学院:以学校通报为准
  • 优质文化资源下基层,上海各区优秀群文团队“文化走亲”