c++ - 为什么即使使用指定的 std::launch::async 标志,std::async 也会同步调用该函数

标签 c++ multithreading asynchronous

我传递给 std::async 的函数打印当前线程 ID。尽管使用 std::launch::async 标志调用,它仍打印相同的 thead id。这意味着它同步调用该函数。为什么?

void PrintThreadId()
{
    std::cout << std::this_thread::get_id() << std::endl;
}

int main()
{
    for (int i = 0; i < 5; ++i)
    {
        auto f = std::async(std::launch::async, PrintThreadId);
        f.wait();
    }
}

输出是: 20936 20936 20936 20936 20936

环境:VS 2015,W7。

提前致谢!

最佳答案

您实际上通过等待每个调用来序列化调用,因此可以重复使用同一个线程而不会破坏 std::future 由不同于调用者线程

当以下代码显示与其他代码相同的 Caller ThreadId 时,请唤醒我们:

void PrintThreadId()
{
    std::cout << std::this_thread::get_id() << std::endl;
}

int main()
{
    std::cout << "Caller threadId (to be different from any id of the future exec thread): ";
    PrintThreadId();

    for (int i = 0; i < 5; ++i)
    {
        auto f = std::async(std::launch::async, PrintThreadId);
        f.wait();
    }
}

关于c++ - 为什么即使使用指定的 std::launch::async 标志,std::async 也会同步调用该函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40200604/

相关文章:

c++ - Firefox 扩展的多平台部署

c++ - 使用 qSort 对字符串进行排序

multithreading - TensorFlow队列运行器如何工作?

c++ - 如何使用 SDL2 为每个线程设置一个共享的 OpenGL 上下文?

c++ - 如何锁定队列变量地址而不是使用临界区?

excel - 从 VSTO Excel 插件异步调用进程内 COM-DLL?

python - 这两种基于生成器的协程是同一个概念吗?

C++ 从 .txt 读取文件并使用 Xcode 在新的 .txt 中保存所需的值

c++ - 使用新对象重新分配 `unique_ptr` 值的便捷类型推断方法

javascript - 使用 jQuery 的 Deferred 管理同步和异步 JavaScript 函数