C++中的future和promise使用方法

文章详细介绍了C++11中的std::future和std::promise机制,用于处理异步操作的结果。std::future允许以同步方式等待异步操作的结果,而std::promise则用来设置值供future读取,实现线程间的同步。文中通过示例代码展示了如何使用wait_for函数等待特定时间,以及如何设置和获取promise的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

future和promise

C++11中std::future提供了一种访问异步操作结果的机制。异步操作不能马上就获取操作结果,只能在未来某个时候获取,但可以以同步等待的方式来获取结果,可以通过查询future的状态(future_status)来获取异步操作的结果。
std::promise 对象可以保存某一类型 T 的值,该值可被 future 对象读取(可能在另外一个线程中),因此 promise 也提供了一种线程同步的手段。在 promise 对象构造时可以和一个共享状态(通常是std::future)相关联,并可以在相关联的共享状态(std::future)上保存一个类型为 T 的值。可以通过 get_future 来获取与该 promise 对象相关联的 future 对象,调用该函数之后,两个对象共享相同的共享状态(shared state)。

  • deferred:异步操作还没开始
  • ready:异步操作已经完成
  • timeout:异步操作超时
  1. future函数:
    **get():**获取future所得到的结果,如果异步操作还没有结束,那么会在此等待异步操作的结束,并获取返回的结果。
    **wait()😗*等待异步操作的结束状态变为ready,不能获得返回结果。
    **wait_for(timeout)😗*等待timeout时间后返回结果,如果超时返回状态status=timeout。
  2. promise函数
    set_value():设置共享状态的值,此后 promise 的共享状态标志变为 ready
    get_future:获取与promise对象关联的对象
    set_exception:为promise设置异常,此后promise的共享状态标识变为ready
    set_value_at_thread_exit :在线程退出时该 promise 对象会自动设置为 ready(注意:该线程已设置promise的值,如果在线程结束之后有其他修改共享状态值的操作,会抛出future_error(promise_already_satisfied)异常)
    swap:交换 promise 的共享状态
    使用示例:

```cpp
include <iostream>
#include <future>
#include <thread>
#include <unistd.h>
#include<chrono>
void set_promise(std::promise<int>& p) {
    std::cout << "set_promise begin." << std::endl;
    sleep(5);
    p.set_value(100); 
    std::cout << "set_promise end." << std::endl;
}
 
int main() {
    std::promise<int> p;
    // 将promise和future绑定,这一步就是允诺future,未来会有人对promise赋值
    std::future<int> f = p.get_future();
    std::thread t(&set_promise, std::ref(p));
    std::cout<<"wait ready111:" << std::endl;
    auto status = f.wait_for(std::chrono::milliseconds(1000));//等待1s,结束等待时状态未改变,返回值为timeout
    std::cout<<"wait ready222:" << static_cast<int>(status) <<std::endl;
    status = f.wait_for(std::chrono::milliseconds(5000));//等待5s,结束等待时,状态已经变为ready
    std::cout<<"wait ready333:" << static_cast<int>(status) <<std::endl;
    std::cout << f.get() << std::endl;    // 通过get 拿到promise set的value
t.join();
return 0;
}
参考文章:
https://blog.youkuaiyun.com/whl0071/article/details/126251922
https://zhuanlan.zhihu.com/p/448035015
### C++中`std::future``std::promise`的使用方法及区别 #### `std::future`与`std::promise`概述 在C++11标准库中引入了`std::future``std::promise`来支持异步编程模型。这两个组件共同实现了所谓的“承诺-未来”模式,其中`std::promise`负责存储并最终化某个值或异常的状态,而`std::future`则允许其他线程获取这个状态的结果。 #### 关键特性说明 - **单一关联性**:一个`std::promise`实例只能创建一个对应的`std::future`对象[^4]。 - **不可重复赋值**:一旦通过`set_value()`设置了`std::promise`中的值,则不能再更改此值;同样地,对于同一`std::promise`多次调用`get_future()`将会引发错误。 #### 使用场景描述 通常情况下,在多线程环境中,如果有一个生产者线程需要向消费者线程传递数据或者通知某些事件的发生时可以采用这种方式。例如: ```cpp #include <iostream> #include <thread> #include <chrono> #include <future> void producer(std::promise<int>& prom) { try { // Simulate some work being done by the thread. std::this_thread::sleep_for(std::chrono::seconds(2)); int result = 42; prom.set_value(result); // Set value to be retrieved later via future object } catch (...) { prom.set_exception(std::current_exception()); } } int main() { std::promise<int> myPromise; auto fut = myPromise.get_future(); // Get a handle on the promised data std::thread t(producer, std::ref(myPromise)); // Wait until we have access to the shared state's value or exception try { int val = fut.get(); std::cout << "Value received from another thread: " << val << '\n'; } catch (const std::exception& e) { std::cerr << "Exception caught: " << e.what() << "\n"; } if(t.joinable()) t.join(); return 0; } ``` 上述代码展示了如何利用`std::promise`在线程之间安全地传输整数值,并且展示了一个简单的异常处理机制。这里的关键在于理解`myPromise.set_value(result)`是如何将结果发送给等待它的主线程上的`fut.get()`调用[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值