第11章 C++并发进阶:std::thread、std::async、std::future、std::promise、线程池实现

并发编程,说白了就是让程序同时干多件事。很多新手一上来就想着用锁、用原子变量,结果代码写得跟迷宫似的。我个人习惯是,先搞清楚C++标准库给我们提供了哪些并发工具,再谈怎么用。

这一章,我们聊聊C++并发编程的几个核心组件:std::threadstd::asyncstd::futurestd::promise,以及怎么手写一个线程池。嗯,这些工具用好了,你的程序性能能上一个台阶。

11.1 std::thread:最基础的线程管理

std::thread是C++11引入的线程类。它封装了操作系统线程的创建、管理和销毁。说白了,就是让你不用再写pthread_create那种C风格的代码了。

先看一个最简单的例子:

#include <iostream>
#include <thread>

void hello() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(hello);
    t.join();  // 等待线程结束
    return 0;
}

这里有个坑,我刚开始用的时候踩过。线程对象析构时,如果线程还在运行,程序会直接终止。所以要么调用join()等待,要么调用detach()分离。我个人习惯是尽量用join(),因为detach()容易导致资源泄漏。

注意:线程一旦detach,你就再也无法控制它了。如果线程还在访问局部变量,而局部变量已经销毁,那就是未定义行为。我曾经在项目里见过这种bug,排查了整整两天。

11.2 std::async 和 std::future:异步任务的优雅方式

直接操作线程其实挺麻烦的。你要管理线程的生命周期,还要处理线程间的数据传递。这时候,std::asyncstd::future就派上用场了。

std::async会启动一个异步任务,并返回一个std::future对象。你可以通过future获取任务的返回值。这比手动创建线程、传递参数、处理返回值要优雅得多。

#include <iostream>
#include <future>

int compute(int x) {
    return x * x;
}

int main() {
    std::future<int> result = std::async(std::launch::async, compute, 10);
    std::cout << "Result: " << result.get() << std::endl;
    return 0;
}

这里有个细节:std::launch::async表示强制在新线程上执行。如果不指定,默认是std::launch::async | std::launch::deferred,由系统决定是异步执行还是延迟执行。嗯,这可能会导致一些意想不到的行为。

小技巧:如果你不确定任务会不会被延迟执行,可以显式指定std::launch::async。我在项目中遇到过因为默认策略导致任务被延迟执行,结果程序卡住了的情况。

11.3 std::promise:更灵活的值传递

std::promisestd::future是一对搭档。promise负责设置值,future负责获取值。它们之间通过一个共享状态来通信。

你想想看,有时候你需要在多个线程之间传递数据,但又不想用全局变量或者复杂的锁机制。promisefuture就是为此设计的。

#include <iostream>
#include <thread>
#include <future>

void set_value(std::promise<int> p) {
    p.set_value(42);
}

int main() {
    std::promise<int> p;
    std::future<int> f = p.get_future();
    
    std::thread t(set_value, std::move(p));
    std::cout << "Value: " << f.get() << std::endl;
    
    t.join();
    return 0;
}

注意,promise是不能复制的,只能移动。这是因为每个promise对应唯一的共享状态。如果你不小心复制了,编译器会报错。

11.4 线程池实现:从零开始

手动创建线程的开销其实不小。每次创建和销毁线程,都要涉及系统调用,频繁操作会严重影响性能。线程池就是为了解决这个问题——预先创建一批线程,重复利用。

下面是一个简单的线程池实现:

#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>

class ThreadPool {
public:
    ThreadPool(size_t threads) : stop(false) {
        for (size_t i = 0; i < 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();
                }
            });
        }
    }

    template<class F, class... Args>
    auto enqueue(F&& f, Args&&... args) 
        -> std::future<typename std::result_of<F(Args...)>::type> {
        using return_type = typename std::result_of<F(Args...)>::type;
        
        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::unique_lock<std::mutex> lock(queue_mutex);
            if (stop)
                throw std::runtime_error("enqueue on stopped ThreadPool");
            tasks.emplace([task](){ (*task)(); });
        }
        condition.notify_one();
        return res;
    }

    ~ThreadPool() {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            stop = true;
        }
        condition.notify_all();
        for (std::thread &worker : workers)
            worker.join();
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop;
};

这个线程池的核心逻辑其实不复杂:

  • 构造函数创建固定数量的工作线程
  • 每个线程循环等待任务
  • enqueue方法把任务加入队列,并通知一个空闲线程
  • 析构时通知所有线程停止,并等待它们结束

这里有个关键点:std::packaged_task。它把可调用对象包装起来,并关联一个future。这样我们就可以通过future获取任务的返回值了。

核心要点:线程池的关键在于任务队列和条件变量的配合使用。任务队列负责存储待执行的任务,条件变量负责线程间的同步和唤醒。

11.5 知识体系总览

为了让你更直观地理解这些组件之间的关系,我画了一张图:

C++并发编程核心组件关系图 std::thread 底层线程管理 std::async 异步任务启动 std::future 获取异步结果 std::promise 设置异步值 线程池 任务队列 + 工作线程 std::thread 是基础,std::async 是便捷封装 std::future 和 std::promise 是值传递的桥梁 线程池基于 std::thread 实现,通过 future 返回结果

11.6 避坑指南

我在实际项目中踩过不少并发编程的坑,这里分享几个常见的:

  • 忘记join或detach:线程对象析构时会调用std::terminate,程序直接崩溃。我曾经在重构代码时漏了一个join,结果线上服务挂了。
  • 死锁:多个线程互相等待对方释放锁。解决办法是尽量使用std::lock一次性锁定多个互斥量,或者按固定顺序加锁。
  • 数据竞争:多个线程同时读写同一变量。用std::atomic或者互斥量保护共享数据。
  • 虚假唤醒:条件变量可能在没有被通知的情况下被唤醒。所以wait的时候一定要用谓词判断。
我的建议:并发编程的调试非常困难。我一般会先在单线程环境下验证逻辑正确性,再切换到多线程。另外,使用std::async代替手动创建线程,能减少很多麻烦。

11.7 性能考量

线程池的线程数量不是越多越好。线程太多会导致上下文切换开销过大,反而降低性能。一般来说,线程数设置为std::thread::hardware_concurrency()返回的值比较合理。

另外,任务粒度也很重要。如果每个任务执行时间太短,线程池的管理开销会超过任务本身的计算时间。我一般建议任务执行时间至少是微秒级别的。

组件 适用场景 性能特点
std::thread 需要精细控制线程生命周期 创建销毁开销大
std::async 简单的异步任务 自动管理线程,但控制力弱
线程池 大量短任务 复用线程,减少开销

嗯,这一章的内容就到这里。并发编程是个大话题,但掌握了这些基础组件,你已经能应对大部分场景了。记住,能用std::async就别手动创建线程,能用线程池就别频繁创建销毁线程。这些经验,都是我在项目里一点点积累出来的。