std::jthread 与协作取消

并发是现代软件的基石。C++20 引入的 std::jthread 将线程管理提升到 RAII 级别,并通过内置的 stop_token 协议,让线程的优雅退出变得标准化且简洁。本节将从线程基础出发,带你掌握安全、可取消的并发编程模式。

1. 线程基础回顾

为什么需要并发?

现代 CPU 普遍拥有多核架构——即使是手机芯片也有 4-8 个核心。单线程程序只能利用其中一个核心,其余核心处于空闲状态。并发编程让我们能够:

  • 提升吞吐量——将独立任务分配到不同核心并行执行
  • 降低延迟——耗时的 I/O 操作不阻塞主线程
  • 响应性——UI 线程保持流畅,计算在后台进行

硬件线程 vs 软件线程

理解两个层面的"线程"至关重要:

  • 硬件线程(Hardware Threads):CPU 能够真正同时执行的指令流数量。一个 8 核 CPU(无超线程)有 8 个硬件线程。
  • 软件线程(Software Threads):操作系统调度的执行单元。可以创建远多于硬件线程数的软件线程,OS 通过时间片轮转来调度它们。

原则:CPU 密集型任务的线程数应接近硬件线程数;I/O 密集型任务可以适当超额,因为线程大部分时间在等待。

2. std::jthread vs std::thread

C++11 引入了 std::thread,但它有一个严重的安全隐患——如果线程对象析构时仍处于 joinable 状态,程序会调用 std::terminate() 而直接崩溃。开发者必须手动调用 join() 或 detach()。

C++20 的 std::jthread("j" 代表 "joining")彻底解决了这个问题:

特性 std::thread (C++11) std::jthread (C++20)
析构行为 若 joinable 则 terminate() 自动 request_stop() + join()
取消支持 无内置机制 内置 stop_token
RAII 安全 需手动管理 完全 RAII
异常安全 异常路径易遗漏 join 析构自动处理
头文件 <thread> <thread>

std::thread 的危险示例

#include <thread>
#include <iostream>
#include <stdexcept>

void worker() {
    std::cout << "Working...\n";
}

void dangerous() {
    std::thread t(worker);

    // 如果这里抛出异常...
    throw std::runtime_error("oops");

    t.join();  // 永远执行不到!
    // t 析构时仍是 joinable → std::terminate() → 程序崩溃
}

std::jthread 的安全版本

#include <thread>
#include <iostream>
#include <stdexcept>

void worker() {
    std::cout << "Working...\n";
}

void safe() {
    std::jthread t(worker);

    // 即使这里抛出异常...
    throw std::runtime_error("oops");

    // t 析构时:自动 request_stop() → 自动 join()
    // 线程安全结束,无崩溃
}

永远优先选择 std::jthread。除非你需要与 C++11/14/17 兼容,否则没有理由再使用 std::thread。jthread 消除了一整类线程生命周期 bug。

3. 创建和运行线程

基本创建方式

#include <thread>
#include <iostream>

// 方式 1:普通函数
void hello() {
    std::cout << "Hello from thread " << std::this_thread::get_id() << "\n";
}

int main() {
    std::jthread t1(hello);  // 线程立即开始运行
    // t1 在此作用域结束时自动 join
}

Lambda 线程

#include <thread>
#include <iostream>

int main() {
    int data = 42;

    // 方式 2:Lambda(最常用)
    std::jthread t2([&data] {
        std::cout << "Data = " << data << "\n";
    });

    // 方式 3:带参数的 Lambda
    std::jthread t3([](int x, int y) {
        std::cout << "Sum = " << x + y << "\n";
    }, 10, 20);  // 参数在构造时传入
}

传递参数的注意事项

#include <thread>
#include <string>
#include <iostream>

void process(const std::string& msg) {
    std::cout << msg << "\n";
}

int main() {
    std::string greeting = "Hello, concurrency!";

    // 参数会被拷贝到线程内部存储中
    // 即使函数签名是 const&,线程仍拥有一份拷贝
    std::jthread t(process, greeting);

    // 如果要传引用,必须显式使用 std::ref
    // std::jthread t2(process, std::ref(greeting));
    // 但要确保 greeting 的生命周期覆盖线程执行期!
}

最佳实践:优先使用 Lambda 捕获来传递数据,语义比函数参数更清晰。用 [=] 拷贝或 [&] 引用(引用时需保证生命周期)。

4. stop_token 协作取消

多线程程序的一个核心挑战是:如何优雅地通知一个正在运行的线程"请停下来"?强制终止线程(如 POSIX 的 pthread_cancel)极其危险——可能在持有锁时被杀死,导致死锁和资源泄漏。

C++20 引入了协作取消(Cooperative Cancellation)机制:线程自己定期检查是否被请求停止,然后自行清理并退出。

三大组件

  • std::stop_source:发出停止请求的信号源("发送端")
  • std::stop_token:检查是否已被请求停止的令牌("接收端")
  • std::stop_callback:停止请求到达时自动执行的回调

基本用法:jthread 自动传入 stop_token

#include <thread>
#include <iostream>
#include <chrono>

using namespace std::chrono_literals;

int main() {
    // 如果可调用对象的第一个参数是 std::stop_token,
    // jthread 会自动将其内部的 stop_token 传入
    std::jthread worker([](std::stop_token stoken) {
        int count = 0;
        while (!stoken.stop_requested()) {  // 轮询检查
            std::cout << "Working... " << ++count << "\n";
            std::this_thread::sleep_for(200ms);
        }
        std::cout << "Worker received stop request, cleaning up.\n";
    });

    std::this_thread::sleep_for(1s);  // 让 worker 运行一会儿

    worker.request_stop();  // 发出取消请求(非阻塞)
    // worker 析构时自动 join,等待线程实际退出
    std::cout << "Main: worker stopped gracefully.\n";
}

输出类似于:

Working... 1
Working... 2
Working... 3
Working... 4
Working... 5
Worker received stop request, cleaning up.
Main: worker stopped gracefully.

手动使用 stop_source 和 stop_token

#include <thread>
#include <stop_token>
#include <iostream>
#include <chrono>
#include <vector>

using namespace std::chrono_literals;

int main() {
    // 手动创建 stop_source,多个线程共享同一取消信号
    std::stop_source ssource;

    auto task = [](std::stop_token stoken, int id) {
        while (!stoken.stop_requested()) {
            std::cout << "Thread " << id << " running\n";
            std::this_thread::sleep_for(300ms);
        }
        std::cout << "Thread " << id << " stopping\n";
    };

    // 多个线程共享同一个 stop_token
    std::jthread t1(task, ssource.get_token(), 1);
    std::jthread t2(task, ssource.get_token(), 2);
    std::jthread t3(task, ssource.get_token(), 3);

    std::this_thread::sleep_for(1s);

    // 一次调用,所有线程同时收到停止请求
    ssource.request_stop();
    std::cout << "All threads notified to stop.\n";
}

stop_callback:注册取消回调

#include <thread>
#include <stop_token>
#include <iostream>
#include <chrono>
#include <fstream>

using namespace std::chrono_literals;

int main() {
    std::jthread worker([](std::stop_token stoken) {
        // 注册回调:当 stop 被请求时执行
        std::stop_callback cb(stoken, [] {
            std::cout << "[Callback] Stop requested! Flushing buffers...\n";
        });

        // 模拟工作循环
        while (!stoken.stop_requested()) {
            std::this_thread::sleep_for(100ms);
        }
        std::cout << "[Worker] Exiting.\n";
    });

    std::this_thread::sleep_for(500ms);
    worker.request_stop();
    // 回调在 request_stop() 调用线程上同步执行
}

stop_callback 的执行时机:如果在注册时停止已经被请求,回调立即执行;否则在 request_stop() 被调用时在调用方线程上同步执行。回调在 stop_callback 对象存活期间有效,对象销毁时自动注销。

5. 线程与数据共享

多线程编程中最常见也最危险的错误就是数据竞争(Data Race):多个线程同时访问同一内存位置,且至少一个是写操作,且没有同步机制——这是未定义行为(UB)。

数据竞争示例

#include <thread>
#include <iostream>
#include <vector>

int main() {
    int counter = 0;  // 共享可变状态

    auto increment = [&counter]() {
        for (int i = 0; i < 100000; ++i) {
            ++counter;  // 数据竞争!UB!
        }
    };

    std::jthread t1(increment);
    std::jthread t2(increment);

    t1.join();
    t2.join();

    // 期望 200000,实际结果不确定
    // 可能是 143726,可能是 187451,也可能恰好是 200000
    std::cout << "Counter = " << counter << "\n";
}

数据竞争是未定义行为,不是"偶尔得到错误结果"。编译器可以假设 UB 不存在并据此优化代码——你的程序可能在 Debug 模式下看似正确,但 Release 优化后表现出完全不同的行为。

安全策略概览

消除数据竞争的方法有三种:

  1. 互斥锁(Mutex):最通用,下一节详解
  2. 原子操作(Atomic):无锁,适合简单计数器/标志位(5-3 节)
  3. 不共享:每个线程拥有自己的数据副本,最终合并结果
#include <thread>
#include <atomic>
#include <iostream>

int main() {
    // 策略 2:原子操作(简单场景推荐)
    std::atomic<int> counter{0};

    auto increment = [&counter]() {
        for (int i = 0; i < 100000; ++i) {
            ++counter;  // 原子操作,安全
        }
    };

    std::jthread t1(increment);
    std::jthread t2(increment);

    t1.join();
    t2.join();

    std::cout << "Counter = " << counter << "\n";  // 保证 200000
}

6. 硬件并发度

创建多少线程最合适?这取决于任务类型和硬件能力。C++ 标准库提供了查询硬件并发度的接口:

#include <thread>
#include <iostream>

int main() {
    unsigned int n = std::jthread::hardware_concurrency();
    // 返回硬件支持的并发线程数
    // 通常等于 CPU 核心数 × 超线程倍数
    // 如果无法检测,返回 0

    std::cout << "Hardware concurrency: " << n << "\n";
    // 典型输出:8(4 核 8 线程笔记本)
}

选择线程数的经验法则

任务类型 推荐线程数 原因
CPU 密集型(计算、渲染) hardware_concurrency() 超出则线程切换成本 > 收益
I/O 密集型(网络、磁盘) hardware_concurrency() * 2~4 线程多数时间在等待 I/O
混合型 通过基准测试确定 因负载特征而异
#include <thread>
#include <vector>
#include <numeric>
#include <iostream>

// 并行求和:根据硬件并发度分配线程
long long parallel_sum(const std::vector<int>& data) {
    const unsigned int num_threads =
        std::max(1u, std::jthread::hardware_concurrency());
    const size_t chunk_size = data.size() / num_threads;

    std::vector<long long> partial_sums(num_threads, 0);
    std::vector<std::jthread> threads;

    for (unsigned int i = 0; i < num_threads; ++i) {
        size_t start = i * chunk_size;
        size_t end = (i == num_threads - 1) ? data.size() : start + chunk_size;

        threads.emplace_back([&data, &partial_sums, i, start, end] {
            for (size_t j = start; j < end; ++j) {
                partial_sums[i] += data[j];
            }
        });
    }

    threads.clear();  // jthread 析构 → 自动 join 所有线程

    return std::accumulate(partial_sums.begin(), partial_sums.end(), 0LL);
}

int main() {
    std::vector<int> data(10'000'000, 1);
    std::cout << "Sum = " << parallel_sum(data) << "\n";  // 10000000
}

注意:上面的并行求和示例中每个线程写自己的 partial_sums[i],不存在数据竞争。但相邻元素可能在同一缓存行上,会导致"伪共享(false sharing)"降低性能——高性能场景需要填充对齐。

7. 实用模式

模式 A:可取消的后台工作器

#include <thread>
#include <queue>
#include <mutex>
#include <iostream>
#include <chrono>

using namespace std::chrono_literals;

class BackgroundWorker {
    std::jthread thread_;

public:
    BackgroundWorker() : thread_([this](std::stop_token stoken) {
        std::cout << "[Worker] Started.\n";
        while (!stoken.stop_requested()) {
            // 模拟处理任务
            std::cout << "[Worker] Processing...\n";
            std::this_thread::sleep_for(500ms);
        }
        std::cout << "[Worker] Shutting down gracefully.\n";
    }) {}

    // 析构时 jthread 自动 request_stop() + join()
    // 无需手动管理!

    void stop() { thread_.request_stop(); }
};

int main() {
    {
        BackgroundWorker w;
        std::this_thread::sleep_for(2s);
        // w 离开作用域 → 析构 → 自动停止并等待线程结束
    }
    std::cout << "[Main] Worker destroyed safely.\n";
}

模式 B:周期性任务

#include <thread>
#include <iostream>
#include <chrono>
#include <functional>

using namespace std::chrono_literals;

// 通用周期性执行器
std::jthread make_periodic(std::chrono::milliseconds interval,
                           std::function<void()> task) {
    return std::jthread([interval, task = std::move(task)]
                        (std::stop_token stoken) {
        while (!stoken.stop_requested()) {
            task();
            // 使用短暂 sleep 循环代替长 sleep,以快速响应取消
            auto deadline = std::chrono::steady_clock::now() + interval;
            while (std::chrono::steady_clock::now() < deadline) {
                if (stoken.stop_requested()) return;
                std::this_thread::sleep_for(50ms);
            }
        }
    });
}

int main() {
    int tick = 0;
    auto heartbeat = make_periodic(1s, [&tick] {
        std::cout << "Heartbeat #" << ++tick << "\n";
    });

    std::this_thread::sleep_for(5s);
    heartbeat.request_stop();
    // 或直接让 heartbeat 离开作用域
}

模式 C:生产者线程

#include <thread>
#include <queue>
#include <mutex>
#include <iostream>
#include <chrono>
#include <optional>

using namespace std::chrono_literals;

template <typename T>
class ThreadSafeQueue {
    std::queue<T> queue_;
    mutable std::mutex mtx_;
public:
    void push(T value) {
        std::lock_guard lock(mtx_);
        queue_.push(std::move(value));
    }

    std::optional<T> try_pop() {
        std::lock_guard lock(mtx_);
        if (queue_.empty()) return std::nullopt;
        T value = std::move(queue_.front());
        queue_.pop();
        return value;
    }

    bool empty() const {
        std::lock_guard lock(mtx_);
        return queue_.empty();
    }
};

int main() {
    ThreadSafeQueue<int> queue;

    // 生产者:持续生产数据直到被取消
    std::jthread producer([&queue](std::stop_token stoken) {
        int value = 0;
        while (!stoken.stop_requested()) {
            queue.push(++value);
            std::this_thread::sleep_for(100ms);
        }
        std::cout << "[Producer] Stopped after producing "
                  << value << " items.\n";
    });

    // 消费者:持续消费数据
    std::jthread consumer([&queue](std::stop_token stoken) {
        int consumed = 0;
        while (!stoken.stop_requested() || !queue.empty()) {
            if (auto val = queue.try_pop()) {
                ++consumed;
                // 处理 *val ...
            } else {
                std::this_thread::sleep_for(50ms);
            }
        }
        std::cout << "[Consumer] Consumed " << consumed << " items.\n";
    });

    std::this_thread::sleep_for(2s);

    producer.request_stop();  // 先停生产者
    producer.join();          // 等生产者退出

    consumer.request_stop(); // 再停消费者(它会先消费完剩余数据)
}

生产者-消费者模式的取消顺序很重要:先停止生产者,再停止消费者。消费者的循环条件 !stoken.stop_requested() || !queue.empty() 确保它会消费完队列中的剩余数据再退出。

本节小结

  • std::jthread 是 std::thread 的安全替代——析构时自动 request_stop() + join(),彻底消除线程泄漏
  • 线程函数的第一个参数若为 std::stop_token,jthread 会自动注入
  • stop_source / stop_token / stop_callback 三者构成标准化的协作取消协议
  • 在循环中调用 stoken.stop_requested() 是最常见的取消检查模式
  • 共享可变数据是数据竞争的根源——需要互斥锁或原子操作来保护(下一节详解)
  • 使用 hardware_concurrency() 查询硬件并发度以合理分配线程数