Search code examples
c++condition-variablestd-future

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


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.


Solution

  • 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.