c++multithreadingstdasync

std::launch::async does the number of distinct thread is correct?


I was reading abut std::async with std::launch::async and read that with that policy, the callable will be called in a new thread.

So for sake of test, I did as follow:

struct Wrapper
    {   
        void consume()
        {
             std::cout << "consume " << std::this_thread::get_id() << std::endl;
            std::for_each(arr.begin(), arr.end(), [](int val) {std::cout << val; });
        }

        bool produce()
        {
            std::cout << "produce " << std::this_thread::get_id() << std::endl;

            arr = { 1,0,3 };
            return true;
        }
    };


    int main()
    {

        std::cout << "main " << std::this_thread::get_id() << std::endl;

        Wrapper wrap;
        std::future<bool> fut = std::async(std::launch::async, &Wrapper::produce, &wrap);

        if (fut.get())
            std::async(std::launch::async, &Wrapper::consume, &wrap);

    }

So based on that, I will excpect 3 threads :

when I run the program i got :

enter image description here

Why is the two calls of the std::async have the same thread ID ??

Thank you.


Solution

  • The standard says about std::async :

    If launch​::​async is set in policy, calls INVOKE(DECAY_­COPY(std​::​forward<F>(f)), DECAY_­COPY(std​::​forward<Args>(args))...) as if in a new thread of execution [...]

    Link

    The important part is "as if in a new thread of execution". The implementation must behave as if the callable object was called from a new thread, but it's not required to actually run on a new thread. This leeway is provided so that the standard library implementer can reuse the same threads, perhaps by keeping a handy pool of threads on standby (a threadpool pattern), which can be more responsive than creating and destroying threats for every call to std::async. Though in theory an implementation could also choose to create and destroy threads each time, or do anything else that respects the requirements of the standard.