Does std::promise internally use std::condition_variable to notify the associated std::future?
Asked Answered
B

1

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.

Britzka answered 7/6, 2019 at 7:44 Comment(5)
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.Twenty
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?Britzka
Yes sure, just read the source. Note this is not what you have asked.Twenty
Could you please point out the source? I only found the website in the question. Thanks!Britzka
Are you asking where to download the source of gcc? Have you tried to google "download gcc source"?Twenty
V
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.

Vining answered 7/6, 2019 at 9:3 Comment(3)
Thank you very much for the detailed explanation! I have another question: I check the sizeof(std::condition_variable) and sizeof(std::promise<void>) 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.Britzka
@Britzka __asoc_state is a shared state, so promise only holds a pointer to it.Vining
I see. Very appreciate your patience and answering!Britzka

© 2022 - 2024 — McMap. All rights reserved.