c++ - 在 C++14 中,可恢复函数将在什么情况下执行?

标签 c++ asynchronous future c++14

C++14 的提议之一是Resumable Functions它为 C++ 提供了当今 C# 中可用的异步/等待机制。基本思想是可以暂停一个函数 在等待异步操作完成时。当异步操作完成时,函数可以在暂停的地方恢复。这是以非阻塞方式完成的,因此调用可恢复函数的线程不会被阻塞。

对我来说,函数将在哪个上下文(线程)中恢复并不明显。它会由暂停函数的线程恢复(据我所知,这是在 C# 中完成的)还是使用另一个线程?

如果它被暂停的线程恢复,是否必须将线程置于某种特殊状态或调度程序会处理这个?

最佳答案

引用 N3564:

After suspending, a resumable function may be resumed by the scheduling logic of the runtime and will eventually complete its logic, at which point it executes a return statement (explicit or implicit) and sets the function’s result value in the placeholder.

It should thus be noted that there is an asymmetry between the function’s observed behavior from the outside (caller) and the inside: the outside perspective is that function returns a value of type future at the first suspension point, while the inside perspective is that the function returns a value of type T via a return statement, functions returning future/shared_future behaving somewhat different still.

A resumable function may continue execution on another thread after resuming following a suspension of its execution.

这基本上意味着

  • 第一次调用时,可恢复函数在其调用者的线程上下文中执行。
  • 在每个暂停点之后,实现可以自由选择在哪个线程上继续执行可恢复函数
  • 从调用代码的角度来看,可恢复函数的工作方式类似于异步函数,其中部分(可观察的)行为在函数调用返回时可靠地执行,但最终结果可能尚未出现(返回 future<T> 不必处于就绪状态)。
  • 作为一名程序员,您不必为了恢复可恢复的功能而费尽心思。

关于c++ - 在 C++14 中,可恢复函数将在什么情况下执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16882055/

相关文章:

基于 C++ 策略的设计

c++ - 在 C++ 中实现 sql 语句绑定(bind)的最佳方法

c++ - lib-mingw和lib-vc2019有什么区别

javascript - 如何使这个同步递归函数异步

javascript - 如何在 then 语句中返回一组 promise

javascript - 调用数量可变且相互依赖的异步函数

c++ - 为什么编译超过100,000行的std::vector::push_back需要很长时间?

java - 在日期/时间调用方法

async-await - 如何在新的 future API 中删除 future 的类型?

Java 并发 : Is cancelling Futures necessary for them to be Garbage Collected?