multithreading - C++11 线程与异步

标签 multithreading c++11 stdthread stdasync

考虑以下我试图启动 10000 个线程的两个代码片段:

片段 1

    std::array<std::future<void>, 10000> furArr_;
    try
    {
        size_t index = 0;
        for (auto & fut : furArr_)
        {
            std::cout << "Created thread # " << index++ << std::endl;
            fut = std::async(std::launch::async, fun);
        }
    }
    catch (std::system_error & ex)
    {
        std::string str = ex.what();
        std::cout << "Caught : " << str.c_str() << std::endl;
    }
    // I will call get afterwards, still 10000 threads should be active by now assuming "fun" is time consuming

片段 2
    std::array<std::thread, 10000> threadArr;
    try
    {
        size_t index = 0;
        for (auto & thr : threadArr)
        {
            std::cout << "Created thread # " << index++ << std::endl;
            thr = std::thread(fun);
        }
    }
    catch (std::system_error & ex)
    {
        std::string str = ex.what();
        std::cout << "Caught : " << str.c_str() << std::endl;
    }

第一种情况总是成功。即我能够创建 10000 个线程,然后我必须等待所有线程完成。在第二种情况下,在创建 1600 多个线程后,我几乎总是最终得到一个异常(“资源不可用再试一次”)。

使用 std::launch::async 的启动策略,我认为这两个片段的行为方式应该相同。使用 async 启动策略的 std::async 与显式使用 std::thread 启动线程有何不同?

我在 Windows 10,VS2015 上,二进制文件是在 x86 Release模式下构建的。

最佳答案

首先感谢 Igor Tandetnik给我这个答案的方向。
当我们使用 std::async (使用异步启动策略),我们说:

“I want to get this work done on a separate thread”.


当我们使用 std::thread我们在说:

“I want to get this work done on a new thread”.


细微的差别意味着 async (通常)使用线程池实现。这意味着如果我们使用 async 调用了一个方法多次,通常该方法中的线程 ID 会重复,即 async将多个作业分配给池中的同一组线程。而与 std::thread ,永远不会。
这种差异意味着与使用 async 相比,显式启动线程可能会占用更多资源(因此是异常)。与 async启动政策。

关于multithreading - C++11 线程与异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44689106/

相关文章:

c++ - 如果我没有收到来自客户端的消息,如何每 20 秒打印一次日期时间

c++ - 已知大小时向 vector 添加元素的基准测试

multithreading - Thread_Guard类中std::thread引用的默认值是多少?

C++:Boost.Asio:在新线程中启动 SSL 服务器 session

Java 线程不会暂停 I/O 操作

c# - 处理在辅助线程过程中发生的未处理错误

c++ - 将 boost::make_recursive_variant 与元组一起使用

c++ - 在 Qt Creator 中使用 C++11

c++ - 使用变量类型的 std::function 运行线程

java - JMeter 为什么添加 Constant Timer 后错误率降低了