温馨提示×

如何在C++中实现异步操作

c++
小樊
82
2024-08-17 17:48:36
栏目: 编程语言

在C++中实现异步操作有多种方法,以下是其中一种使用std::async的简单示例:

#include <iostream>
#include <future>
#include <chrono>

int fetchData() {
    // 模拟耗时操作
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}

int main() {
    // 使用std::async创建一个异步任务
    std::future<int> future_result = std::async(std::launch::async, fetchData);

    // 在主线程中可以执行其他操作

    // 获取异步操作的结果
    int result = future_result.get();
    
    // 输出结果
    std::cout << "Result: " << result << std::endl;

    return 0;
}

在上面的示例中,fetchData函数模拟了一个耗时的操作,通过std::async创建了一个异步任务,并在主线程中执行其他操作。最后通过future_result.get()获取异步操作的结果。其他的实现方法还有使用std::threadboost::asio等。

0