(14)std::async

std::async 是 C++11 提供的高级异步操作接口,用于启动一个异步任务,并自动返回一个 std::future 来获取结果。
#include <future>
#include <iostream>

int heavy_computation() {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}

int main() {
    // 启动异步任务
    std::future<int> fut = std::async(std::launch::async, heavy_computation);

    std::cout << "Doing other work...\n";

    int result = fut.get(); // 阻塞等待结果
    std::cout << "Result: " << result << std::endl;

    return 0;
}
posted @ 2019-06-24 22:47  osbreak  阅读(165)  评论(0)    收藏  举报