繁体   English   中英

std::launch::async 不同线程的数量是否正确?

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

我正在阅读 std::async 与 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 的第一次调用(执行 produce fct)
  • 线程 3:std::async 的第二次调用(执行 consume fct)

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

在此处输入图像描述

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

谢谢你。

标准说关于std::async

如果在policy设置了launch​::​async ,则调用INVOKE(DECAY_COPY(std​::​forward<F>(f)), DECAY_COPY(std​::​forward<Args>(args))...)就像在新的执行线程中一样[...]

链接

重要的部分是“ 好像在新的执行线程中”。 该实现必须表现得好像是从新线程中调用了可调用对象,但实际上并不需要在新线程上运行它。 提供此回旋余地,这样的标准库的实现可以重复使用相同的线程,也许是通过保持待命线程池得心应手(A 线程池模式),可以比创建和每次调用破坏的威胁更加敏感std::async 尽管从理论上讲,实现也可以选择每次创建和销毁线程,或者执行任何其他符合标准要求的事情。

试试这个,有三个线程

    #include<future>
    #include<iostream>
    #include<array>
    #include<algorithm>
    #include<thread>
    #include<vector>

    std::array<int, 100000> arr;
    int sum=0;

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

        void produce()
        {
            std::cout << "producer:" <<std::this_thread::get_id() << std::endl;
            
            int a=0;
            while(true)
            {
                if(a++>1e9)
                {
                    break;
                }
            }
        }
    };


    int main()
    {
        std::fill(arr.begin(), arr.end(), 1);

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

        Wrapper wrap;

        std::vector<std::future<void>> vec;
        vec.push_back(std::async(std::launch::async, &Wrapper::produce, &wrap));
        vec.push_back(std::async(std::launch::async, &Wrapper::consume, &wrap));

        #ifdef WAIT  //Is there any potencial problem if the block below does not run?
        for(auto& future:vec)
        {
            future.get();
        }
        #endif
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM