c++ - 标准 C++11 是否保证 std::async(std::launch::async, func) 在单独的线程中启动 func?

标签 c++ multithreading c++11 asynchronous c++14

标准 C++11 是否保证 std::async(std::launch::async, func) 在单独的线程中启动函数?

C++ 编程语言标准工作草案 2016-07-12:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4606.pdf

<强>1。一方面,C++11-Standard说如果不能创建线程,那么就会出错。这确保了新线程的创建(在没有错误的情况下)。

§ 30.6.8

6

Throws: system_error if policy == launch::async and the implementation is unable to start a new thread.

7 Error conditions:

(7.1) — resource_unavailable_try_again — if policy == launch::async and the system is unable to start a new thread.

文档说:http://en.cppreference.com/w/cpp/thread/launch

std::launch::async a new thread is launched to execute the task asynchronously

<强>2。另一方面,据记载可以可能创建线程。那些,没有必要创建线程。

§ 30.6.8

1 The function template async provides a mechanism to launch a function potentially in a new thread and provides the result of the function in a future object with which it shares a shared state.

这里写的as as if in a new thread,是否意味着不需要在新的单独线程中?

§ 30.6.8

(3.1)

— if policy & launch::async is non-zero — calls INVOKE (DECAY_COPY (std::forward(f)), DECAY_COPY (std::forward(args))...) (20.14.2, 30.3.1.2) as if in a new thread of execution represented by a thread object with the calls to DECAY_COPY () being evaluated in the thread that called async. Any return value is stored as the result in the shared state. Any exception propagated from the execution of INVOKE (DECAY_COPY (std::forward(f)), DECAY_COPY (std::forward(args))...) is stored as the exceptional result in the shared state. The thread object is stored in the shared state and affects the behavior of any asynchronous return objects that reference that state.

当使用 std::async(std::launch::async, func) 时,标准 C++11 是否保证 func() 将在单独的线程,还是可以在调用异步的同一个线程中执行?

最佳答案

这里的两个关键语句是:

as if in a new thread of execution represented by a thread object

The thread object is stored in the shared state and affects the behavior of any asynchronous return objects that reference that state.

“好像”意味着它的行为必须与它为此函数创建了一个 std::thread 对象一样。这意味着创建 std::thread 的所有副作用也必须发生。

话虽如此,如果您将 launch::asynclaunch::deferred 结合使用,则实现将决定是启动新线程还是将其延迟到现有线程一。所以只有 launch::async 需要一个新线程。

关于c++ - 标准 C++11 是否保证 std::async(std::launch::async, func) 在单独的线程中启动 func?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42004877/

相关文章:

c++ - asio 异步服务器不接受连接

c++ - C++ 的自动编码标准违规检测

c# - C# 中是否有与此 Java 代码等效的代码?

c++ - std::unique_lock 移动语义

c++ - std::shared_ptr 是否相互了解?

c++ - Visual Studio 还是 GCC?

c++ - 在线裁判系统

multithreading - Delphi线程异常机制

java - Weblogic Server 11g 上的自定义线程

c++ - 将条件定义与可变参数模板一起使用