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;
}

原文链接: https://www.cnblogs.com/lxzbky/p/17092067.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++future promise

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/315909

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 下午1:58
下一篇 2023年2月16日 下午1:58

相关推荐