C ++ what is std :: shared_future and std :: prom

I understand what std :: future is, but I don't understand when and how to use std :: shared_future and std :: promise, and I couldn't find a good explanation on the internet.

I'll take care of some help wrapping my head around.

By the way, the example here is not entirely clear http://en.cppreference.com/w/cpp/thread/shared_future

+3


source to share


1 answer


std::shared_future

- this is when you need to have multiple valid copies std::future

and possibly multiple consumers of the specified std::future

.

You can move std::future

to std::shared_future

.

Consider std::future

: std::shared_future

as a std::unique_ptr

: std::shared_ptr

.


std::promise

is one way to generate a std::future

.

template<class T>
std::future<std::decay_t<T>> make_ready_future( T&& t ) {
  std::promise<std::decay_t<T>> pr;
  auto r = pr.get_future();
  pr.set_value(std::forward<T>(t));
  return r;
}

      

this is a toy example std::promise

where I take a T

and I create a ready-made one from it std::future<T>

.

If you have code that may require flow segments or may have already been calculated, you can return from it std::future<T>

. If it is not calculated, you return the call result std::async( ... )

. If it's already calculated, you refund make_ready_future( calculated value )

.

A slightly more complicated situation:



template<class T>
struct promise_pipe {
  std::future<T> out;
  std::function<void(T)> in;
  promise_pipe() {
    auto pr = std::make_shared<std::promise<T>>();
    out = pr->get_future();
    in = [pr](T t)mutable{
      if (pr) pr->set_value(std::forward<T>(t));
      pr = {};
    };
  }
};

      

Here I wrote a promise_pipe

.

A promise_pipe<int>

has two fields: a std::future<int> out

and a std::function<void(int)> in

.

The future out

will be ready if and only if you call in

with int

.

So, you might have a function that returns std::future<Bitmap>

. You have network code waiting for bitmap streaming. This way you create promise_pipe<Bitmap>

, return std::future<Bitmap>

and store in

in the "todo" list when you get the bitmap.

When the bitmap is fully arrived, you just execute in(Bitmap)

and someone expects to future

be notified.


promise

are objects designed so that programmers can create their own future

s, not just use those created by the library std

.

Now a is packaged_task

often easier to work with than std::promise

and serves the same purpose.

+5


source







All Articles