C++future promise

A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads.
provider比较抽象,可以是函数可以是类,是别人提供好的东西

A promise is an object that can store a value of type T to be retrieved by a future object (possibly in another thread), offering a synchronization point.

future用于访问异步操作结果
std::async可以异步执行函数,可能是放到另一个线程去执行,返回值是一个future类型
std::promise用于线程同步的工具,储存一些数据,供future获取,协程在运行得到结果后也会将结果写入promise供获取
以async为例
代码来源

#include <iostream>             // std::cout
#include <future>               // std::async, std::future
#include <chrono>               // std::chrono::milliseconds

// a non-optimized way of checking for prime numbers:
bool is_prime(int x)
{
    for (int i = 2; i < x; ++i)
        if (x % i == 0)
            return false;
    return true;
}

int main()
{
    // call function asynchronously:
    std::future < bool > fut = std::async(is_prime, 6666661);

    // do something while waiting for function to set future:
    std::cout << "checking, please wait";
    std::chrono::milliseconds span(100);
    while (fut.wait_for(span) == std::future_status::timeout)
        std::cout << '.';

    bool x = fut.get();         // retrieve return value

    std::cout << "\n6666661 " << (x ? "is" : "is not") << " prime.\n";

    return 0;
}

后面C++20里的协程我猜应该是基于此实现的,理解一下有好处

这里放一下官方promise的代码

#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

void print_int (std::future<int>& fut) {
  int x = fut.get();//获取异步执行结果
  std::cout << "value: " << x << '\n';
}

int main ()
{
  std::promise<int> prom;                      // create promise

  std::future<int> fut = prom.get_future();    // engagement with future

  std::thread th1 (print_int, std::ref(fut));  // send future to new thread

  prom.set_value (10);                         // 模拟fulfill promise
                                               // (synchronizes with getting the future)
  th1.join();
  return 0;
}
posted @ 2023-02-04 17:58  ecnu_lxz  阅读(37)  评论(0编辑  收藏  举报