蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 <future> promise 移动传值、packaged_task、async 启动策略与跨线程异常传播

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-libs-future.cpp
explore-cpp-libs-future.cpp141 行
#include <cmath>
#include <cstdio>
#include <future>
#include <iostream>
#include <stdexcept>
#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

static double compute_square_root(double x) {
    return std::sqrt(x);
}

static void throw_exception_task() {
    throw std::runtime_error("Exception thrown");
}

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

    // Case 1: std::promise moved into worker thread + std::future::get()
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread t([p = std::move(prom)]() mutable {
        p.set_value(10);
    });
    int val1 = fut.get();
    t.join();
    cases.push_back({
        "future_promise_cross_thread",
        std::to_string(10),
        std::to_string(val1),
        val1 == 10
    });

    // Case 2: std::packaged_task moved into std::thread
    std::packaged_task<double(double)> task(compute_square_root);
    std::future<double> res_fut = task.get_future();
    std::thread th(std::move(task), 9.0);
    double root = res_fut.get();
    th.join();
    bool ok2 = std::fabs(root - 3.0) < 1e-9;
    cases.push_back({
        "future_packaged_task_thread",
        lab::jbool(true),
        lab::jbool(ok2),
        ok2
    });

    // Case 3: std::async with std::launch::async and std::launch::deferred
    std::future<int> f_async = std::async(std::launch::async, [](int x) { return x * x; }, 5);
    bool ran_deferred = false;
    std::future<int> f_def = std::async(std::launch::deferred, [&]() {
        ran_deferred = true;
        return 42;
    });
    bool before_get = ran_deferred;
    int v_async = f_async.get();
    int v_def = f_def.get();
    bool after_get = ran_deferred;
    std::string act3 = "async=" + std::to_string(v_async)
        + ";def=" + std::to_string(v_def)
        + ";before=" + std::to_string(before_get ? 1 : 0)
        + ";after=" + std::to_string(after_get ? 1 : 0);
    std::string exp3 = "async=25;def=42;before=0;after=1";
    cases.push_back({
        "future_async_launch_policies",
        lab::esc(exp3),
        lab::esc(act3),
        act3 == exp3
    });

    // Case 4: exception propagation across async future::get()
    std::future<void> f_err = std::async(std::launch::async, throw_exception_task);
    std::string caught_msg;
    try {
        f_err.get();
    } catch (const std::exception& e) {
        caught_msg = e.what();
    }
    cases.push_back({
        "future_exception_propagation",
        lab::esc("Exception thrown"),
        lab::esc(caught_msg),
        caught_msg == "Exception thrown"
    });

    lab::emit(cases);
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/cplusplus-cpp-libs-future-lab/explore-cpp-libs-future.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-libs-future.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2351.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习