C++11中线程间的异步通信

一、std::promise 和 std::future 的基本概念

在C++11中,std::promise 和 std::future 是用于实现异步编程的重要工具。它们提供了一种机制,允许一个线程将值或异常传递给另一个线程,从而实现线程间的数据传递和同步。

std::promise:

  • 是一个模板类,用于存储一个值或异常
  • 可以通过 set_value() 设置值,或者通过 set_exception() 设置异常
  • 与 std::future 关联,用于将结果传递给其他线程。

std::future:

  • 是一个模板类,用于从 std::promise 中获取值或异常。
  • 可以通过 get() 方法获取结果。如果结果尚未准备好,get() 会阻塞当前线程,直到结果可用。
  • 只能获取一次结果,调用 get() 后,future 的状态会变为无效。

二、std::promise 和 std::future 的基本使用

以下是一个简单的示例,展示如何使用 std::promise 和 std::future 在线程间传递数据:

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

void task(std::promise<int> promise) {
   
   
    std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
    promise.set_value(42); // 设置结果
}

int main() {
   
   
    std::promise<int> promise;
    std::future<int> future = promise.get_future(); // 获取与 promise 关联的 future

    std::thread t(task, std::move(promise)); // 启动线程,传递 promise

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

    t.join(); // 等待线程结束
    return 0;
}

使用 std::promise 传递异常:

#include <iostream>
#include <thread>
#include <future>
#include <exception>

void task(std::promise<int> promise) {
   
   
    try {
   
   
        throw std::runtime_error("An error occurred!"); // 抛出异常
    } catch (...) {
   
   
        promise.set_exception(std::current_exception()); // 捕获并传递异常
    }
}

int main() {
   
   
    std::promise<int> promise;
    std::future<int> future = promise.get_future();

    std::thread t(task, std::move(promise));

    try {
   
   
        int result = future.get(); // 尝试获取结果
        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception &e) {
   
   
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    t.join();
    return 0;
}

std::future 的其他用法
wait():

  • 阻塞当前线程,直到结果可用。
  • 不返回结果,仅用于同步。

wait_for() 和 wait_until():

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值