0

我正在阅读 abut std::async with std::launch::async 并使用该策略阅读,可调用将在新线程中调用。

所以为了测试,我做了如下:

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);

    }

因此,基于此,我将期望 3 个线程:

  • 线程1:主线程
  • 线程 2:std::async 的第一次调用(执行生产 fct)
  • 线程3:第二次调用std::async(执行consume fct)

当我运行程序时,我得到:

enter image description here

为什么 std::async 的两个调用具有相同的线程 ID?

谢谢你。

4

1 回答 1

2

该标准说std::async

如果launch​::​async设置在 中,则如同在新的执行线程中policy调用[...]INVOKE(DECAY_­COPY(std​::​forward<F>(f)), DECAY_­COPY(std​::​forward<Args>(args))...)

关联

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.

于 2018-09-14T12:50:08.067 回答