c++ - 异步是否总是在 C++ 中使用另一个线程/核心/进程?

标签 c++ multithreading asynchronous concurrency

据我所知 async 在另一个线程/进程/核心中执行一个函数并且不会阻塞主线程,但总是这样吗?

我有以下代码:

async(launch::async,[]()
{
    Sleep(1000);
    puts("async");
});
puts("main");

它打印async main,那么这是否意味着主线程一直等到async完成?

如果我改为以下:

auto f = async(launch::async,[]() // add "auto f = "
{
    Sleep(1000);
    puts("async");
});
puts("main");

它打印 main async。这看起来好像 main 不等待 async 完成。

最佳答案

As I know async executes a function in another thread/process/core and don't block main thread, but does it happens always?

std::async 仅当 std::launch::async 时才保证在单独的线程上执行作为第一个参数传递:

  • std::launch::async: a new thread is launched to execute the task asynchronously
  • std::launch::deferred the task is executed on the calling thread the first time its result is requested (lazy evaluation)

默认启动策略std::launch::async | std::launch::deferred .


std::async返回 std::future . std::future 's destructor仅当从 std::async 返回 future 时才会阻塞:

these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state


  • 在您的第一个代码片段中,您创建了一个 右值表达式 立即销毁 - 因此 "async"将在 "main" 之前打印.

    1. 异步匿名函数已创建并开始执行。

    2. 异步匿名函数被销毁。

      • main执行被阻塞,直到函数完成。

      • "async"被打印出来了。

    3. main继续执行。

      • "main"已打印。

  • 在您的第二个代码片段中,您创建了一个 左值表达式,其生命周期绑定(bind)到变量 f . f将在 main 结束时销毁函数的范围 - 因此"main"将在 "async" 之前打印由于 Delay(1000) .

    1. 异步匿名函数已创建并开始执行。

      • 有一个 Delay(1000)延迟"async"不会立即被打印出来。
    2. main继续执行。

      • "main"已打印。
    3. main 结束的范围。

    4. 异步匿名函数被销毁。

      • main执行被阻塞,直到函数完成。

      • "async"被打印出来了。

关于c++ - 异步是否总是在 C++ 中使用另一个线程/核心/进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42951452/

相关文章:

c++ - 在处理新的 pthread 时将对象的实例作为参数传递

c# - 使用异步绑定(bind)时如何避免闪烁

scala - 在能够处理其他一些消息之前初始化一个actor

c++ - 从 char 数组到 std::string 的类型推导

c++ - 除非在 XP 兼容模式下运行,否则低级 C++ 应用程序在 Windows Vista/7 上崩溃

使用文本文件中的输入案例进行 C++ 测试

java - 如何安全、及时地处置Java中稀缺的共享资源?

c++ - 在已经初始化我的 2d 矩阵后动态增加行数

python - 在 python 中的线程之间发送消息的推荐方法?

c# - 将参数传递给 WebClient.DownloadFileCompleted 事件