【发布时间】:2021-08-13 16:44:25
【问题描述】:
我有一个关于 co_await 在 C++ 中的工作的问题。我有以下代码 sn-p:-
// Downloads url to cache and
// returns cache file path.
future<path> cacheUrl(string url)
{
cout << "Downloading url.";
string text = co_await downloadAsync(url); // suspend coroutine
cout << "Saving in cache.";
path p = randomFileName();
co_await saveInCacheAsync(p, text); // suspend coroutine
co_return p;
}
int main(void) {
future<path> filePath = cacheUrl("https://localhost:808/");
return 0;
}
co_await 关键字用于暂停任何协程的执行。我们在上面的代码中有 2 个使用它的实例。在主函数中,我们可以访问协程。当程序执行co_await downloadAsync(url) 行时,它会调用downloadAsync 还是暂停协程。
另外,为了执行下一个saveInCacheAsync(p, text) 函数,主函数调用是否应该在协程上恢复?还是会自动调用?
【问题讨论】:
标签: c++ c++20 coroutine c++-coroutine boost-coroutine