为什么std :: async使用相同的线程运行函数

为什么std :: async使用相同的线程运行函数

问题描述:

我正在阅读一篇有关使用c ++进行并发编程的文章(

I was reading an article about concurrent programming with c++ (link). In this article, author shows a code that std::async runs two functions with the same thread. Also, when he used std::future with std::async, it acts differently again and runs all functions with independent threads. Why async behave like that and it has this uncontrolled manner? also, How can I develope a real concurrent program with this feature? is that possible at all or I should miss it?

我建议您也阅读

I suggests to also read the reference, where it is better explained what happens, in the "Notes"-section

如果从std :: async获得的std :: future没有从引用中移出或绑定到引用,则 std :: future的析构函数将在完整表达式的结尾处阻塞 直到异步操作完成 [...]

或者换句话说, std :: async 返回一个 std :: future .一旦返回的对象被销毁,它将等待直到它所代表的运行操作结束.因此,如果您放弃返回值,例如

Or in other words std::async returns a std::future. Once that returned object gets destroyed it will wait until the running operation it represents ends. So, if you discard the return value like

std::async(xyz);

返回值的析构函数在返回后立即被调用,因此等待 xyz 的完成.

The destructor of the returned value gets called immediately after returning and thus waits for the completion of xyz.

如果您将返回值保留为

auto futureXyz = std::async(xyz);

它确实可以并行运行.那是因为返回的值被移到了变量 futureXyz 中,所以局部变量拥有"了并行执行函数.

it does run parallel. That's because the returned value gets moved to the variable futureXyz, so the local variable "owns" the parallel executing function.

我不会称其为无法控制的行为",这只是您不希望看到的,但是定义明确.

I wouldn't call this "uncontrolled behaviour", it's just something you would not expect, but it's well defined.