蓝色天空网mbsky.com · 知识 · 实践 · 创造C++ · 本地阅读预览
教程 / 编程语言 / C++

C++ <thread>

系统讲解 C++11 原生线程库 <thread> 的线程创建、join/detach/joinable 生命周期规则(严正澄清析构未汇合触发 std::terminate),并串联 mutex、condition_variable、future/promise 与 async 并发协作全景。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

线程基本概念与 <thread> 核心组件

线程是操作系统进行 CPU 调度的最小执行单元,同一进程内的多个线程共享地址空间并可并行运行以提升多核吞吐与响应速度。C++11 通过标准头文件 `<thread>` 提供了可移植的原生线程支持,其三大核心组件为:管理单个执行线程的 `std::thread`;提供当前线程休眠(`sleep_for`)、让出时间片(`yield`)与查询标识(`get_id`)的命名空间 `std::this_thread`;以及轻量级线程唯一标识类型 `std::thread::id`。

线程创建、汇合、分离与关键生命周期禁忌

向 `std::thread` 构造函数传入函数、Lambda 或成员函数及其参数后,新线程立即启动运行。调用 `t.join()` 会阻塞当前线程直至子线程结束并回收资源;调用 `t.detach()` 则将线程与对象分离为后台守护线程(分离后不再可 `join`,且开发者必须确保后台线程不再引用已销毁的局部变量)。**必须严格注意**:若一个仍处于可汇合状态(`joinable() == true`)的 `std::thread` 对象离开作用域被析构,C++ 标准会直接调用 `std::terminate()` 强制终止整个进程,而**不会**自动等待或分离;因此任何已启动的 `std::thread` 在析构前都必须明确调用 `join()` 或 `detach()`。

多线程并行计算必须严防**数据竞争(Data Race)**:两个线程同时无同步地修改同一普通全局变量(如 `sum += a + b`)在 C++ 内存模型中属于未定义行为,正确做法是配合 `std::mutex` 或 `std::atomic` 同步访问。同时可通过 `std::this_thread::sleep_for(std::chrono::milliseconds(delay))` 控制线程延时,并在汇合前以 `if (t.joinable()) t.join();` 安全收尾。

并发标准库协作全景与离线多线程实测

现代 C++ 并发并非仅靠 `<thread>` 单打独斗,而是由多个标准头文件协同组成完整工具链:`<thread>` 提供 `std::thread`(核心方法 `join()`、`detach()`、`joinable()`);`<mutex>` 提供互斥锁与 RAII 守卫;`<condition_variable>` 提供事件等待与通知;`<future>` 提供异步结果通道与任务封装。

各组件协同模式如下:`std::mutex` 独占保护共享资源;`std::lock_guard<std::mutex>` 在构造时自动加锁、析构时自动解锁以杜绝遗漏;`std::unique_lock<std::mutex>` 在 RAII 基础上支持中途手动 `unlock()` 与配合条件变量使用;`std::condition_variable` 配合 `unique_lock` 与谓词 `cv.wait(lock, []{ return ready; })` 挂起等待,再由 `notify_all()` 唤醒;`std::promise` 与 `std::future` 实现一次性跨线程结果传递;`std::async` 则一键启动异步计算并返回 `std::future`。本站已在离线 Docker G++ C++17(`-pthread`)环境中真实并发实测线程生命周期、互斥同步求和、条件变量唤醒与 `promise`/`async` 传值。

实测 <thread> 线程创建与 join/detach 生命周期、互斥同步求和、条件变量唤醒及 promise/async

cpp · 阅读源码
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <future>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\b': out += "\\b"; break;
            case '\f': out += "\\f"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

} // namespace lab

int main() {
    std::vector<lab::Case> cases;

    // Case 1: std::thread creation, get_id, joinable, join, detach
    std::thread::id main_id = std::this_thread::get_id();
    std::thread::id id1{}, id2{};
    std::thread t1([&]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
        id1 = std::this_thread::get_id();
    });
    std::thread t2([&]() {
        id2 = std::this_thread::get_id();
    });
    bool j1_before = t1.joinable();
    t1.join();
    t2.join();
    bool j1_after = t1.joinable();

    // Safe detached thread synchronized via promise/future before main exits
    std::promise<int> detach_done;
    auto detach_fut = detach_done.get_future();
    std::thread td([p = std::move(detach_done)]() mutable {
        p.set_value(77);
    });
    bool jd_before = td.joinable();
    td.detach();
    bool jd_after = td.joinable();
    int detach_val = detach_fut.get();

    bool ok1 = j1_before && !j1_after && jd_before && !jd_after
        && (id1 != main_id) && (id2 != main_id) && (detach_val == 77);
    cases.push_back({
        "thread_lifecycle_and_ids",
        lab::jbool(true),
        lab::jbool(ok1),
        ok1
    });

    // Case 2: synchronized parallel sum using mutex + lock_guard (no data race)
    std::mutex sum_mtx;
    int sum = 0;
    auto add_safe = [&](int a, int b) {
        std::lock_guard<std::mutex> lock(sum_mtx);
        sum += a + b;
    };
    std::thread s1(add_safe, 5, 10);
    std::thread s2(add_safe, 5, 10);
    s1.join();
    s2.join();
    cases.push_back({
        "thread_synchronized_parallel_sum",
        std::to_string(30),
        std::to_string(sum),
        sum == 30
    });

    // Case 3: unique_lock manual unlock + condition_variable notify_all
    std::mutex cv_mtx;
    std::condition_variable cv;
    bool ready = false;
    int woken = 0;
    auto waiter = [&]() {
        std::unique_lock<std::mutex> lock(cv_mtx);
        cv.wait(lock, [&]() { return ready; });
        ++woken;
        lock.unlock();
    };
    std::thread w1(waiter);
    std::thread w2(waiter);
    {
        std::unique_lock<std::mutex> lock(cv_mtx);
        ready = true;
    }
    cv.notify_all();
    w1.join();
    w2.join();
    cases.push_back({
        "thread_unique_lock_and_cv_notify",
        std::to_string(2),
        std::to_string(woken),
        woken == 2
    });

    // Case 4: promise/future and std::async square calculation
    std::promise<int> sq_prom;
    std::future<int> sq_fut = sq_prom.get_future();
    std::thread tp([](std::promise<int>&& p, int x) {
        p.set_value(x * x);
    }, std::move(sq_prom), 5);
    int v_prom = sq_fut.get();
    tp.join();
    std::future<int> a_fut = std::async(std::launch::async, [](int x) { return x * x; }, 5);
    int v_async = a_fut.get();
    std::string act4 = "prom=" + std::to_string(v_prom) + ";async=" + std::to_string(v_async);
    std::string exp4 = "prom=25;async=25";
    cases.push_back({
        "thread_promise_future_and_async",
        lab::esc(exp4),
        lab::esc(act4),
        act4 == exp4
    });

    lab::emit(cases);
    return 0;
}
预期结果 · 待实际运行核验
  • 确认子线程 ID 独立且 join/detach 后 joinable 变 false、两线程互斥累加精确等于 30、condition_variable notify_all 唤醒 2 线程、promise 与 async 均精确返回 25。
实测 <thread> 线程创建与 join/detach 生命周期、互斥同步求和、条件变量唤醒及 promise/async

所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

当前源码 SHA256:82382da42a96f30e2119bb38552ca220404d5cd06e9c8e95951917f4abecfa2d

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载C++ <thread>实验

所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

ZIP SHA256:fdfcc977f85bf8b7dabffaf2ae347f377c4026daa2468c10c6b8c82620ad52da

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

如果创建了一个 `std::thread t(worker);` 后既没有调用 `t.join()` 也没有调用 `t.detach()`,当 `t` 离开作用域析构时会发生什么?

展开参考解答

`std::thread` 的析构函数检查到 `joinable() == true` 时会直接调用 `std::terminate()` 异常终止整个程序,而不会自动等待线程结束。

规范与官方依据