8

My question is does std::promise notify the associated std::future through using a std::condition_variable?

I search the source code of std::promise and found this website. But I didn't see std::promise has std::condition_variable in its member data.

Tes
  • 349
  • 3
  • 12
  • 1
    The standard library does whatever is needed to make things work. The standard usually does not specify that it must, or must not, use some specific APIs internally to achieve this. – n. m. could be an AI Jun 07 '19 at 07:57
  • Yes, I understand standard only specifies the required functionality and leaves the implementation to developers. But is it possible to know how GCC implements `std::promise`? – Tes Jun 07 '19 at 08:01
  • Yes sure, just read the source. Note this is not what you have asked. – n. m. could be an AI Jun 07 '19 at 08:01
  • Could you please point out the source? I only found the website in the question. Thanks! – Tes Jun 07 '19 at 08:02
  • Are you asking where to download the source of gcc? Have you tried to google "download gcc source"? – n. m. could be an AI Jun 07 '19 at 08:05

1 Answers1

6

Here's an answer for libc++.

A search for condition_variable in <future> returned exactly one result:

// lines 531 -- 538
class _LIBCPP_TYPE_VIS _LIBCPP_AVAILABILITY_FUTURE __assoc_sub_state
    : public __shared_count
{
protected:
    exception_ptr __exception_;
    mutable mutex __mut_;
    mutable condition_variable __cv_;
    unsigned __state_;

Here __assoc_sub_state is introduced. It is the base class for __assoc_state:

// lines 617 -- 619
template <class _Rp>
class _LIBCPP_AVAILABILITY_FUTURE __assoc_state
    : public __assoc_sub_state

And finally, __assoc_state<_Rp>* is both a member of future<_Rp>:

// lines 1082 -- 1085
template <class _Rp>
class _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FUTURE future
{
    __assoc_state<_Rp>* __state_;

and a member of promise<_Rp>:

// lines 1360 -- 1363
template <class _Rp>
class _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FUTURE promise
{
    __assoc_state<_Rp>* __state_;

So yeah, libc++ std::promise internally uses a std::condition_variable to notify the associated std::future.

L. F.
  • 19,445
  • 8
  • 48
  • 82
  • 1
    Thank you very much for the detailed explanation! I have another question: I check the `sizeof(std::condition_variable)` and `sizeof(std::promise)` and the outputs are 48 and 24. Why is the size of `std::promise` smaller? I am quite confused as I assume the size of a class should be larger than its member data. – Tes Jun 07 '19 at 21:05
  • 1
    @Tes `__asoc_state` is a shared state, so `promise` only holds a pointer to it. – L. F. Jun 08 '19 at 00:57
  • I see. Very appreciate your patience and answering! – Tes Jun 08 '19 at 05:50