lundi 22 juillet 2019

Storage of std::promise

https://en.cppreference.com/w/cpp/thread/promise says that the first specialisation (2) std::promise<R&> is "used to communicate objects between threads". However, I don't know how use this functionality and cannot find any documentation anywhere online. My concern specifically is about storage. If I use std::promise<R&>, where is the object I pass in stored?

According to https://en.cppreference.com/w/cpp/thread/promise/set_value , ...

  • ... std::promise<R> has:
    • set_value(const R &value),
    • set_value(R &&value).
  • ... std::promise<R&> has only:
    • set_value(R &value).

I really think these signatures are odd. I would have expected the right-value reference variant to be part of std::promise<R&> as this one is "used to communicate objects between threads". Communicating an object to another thread sounds like "move it into the associated state, such that the other thread can read it from of the associated state (preventing the object to be destructed as the thread that produced it exits)". However, the value seems to be passed in by reference, instead of moved in. Now what happens if the thread exits?

What is the correct way to communicate objects (instead of primitives) between threads with future/promise? What is a good example using the std::promise<R&> specialisation?

Aucun commentaire:

Enregistrer un commentaire