I had a question regarding the working of co_await in C++. I have the following code snippet:-
// 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;
}
The co_await
keyword is used to suspend the execution of any co-routine. We have 2 instances in the above code where it is used. In the main function, we get access to the co-routine. When the program executes the line co_await downloadAsync(url)
will it invoke downloadAsync
or just suspend the co-routine.
Also, for executing the next saveInCacheAsync(p, text)
function, should the main function call resume on the co-routine ? Or will it get called automatically ?
The coroutine model in C++ is opaque: the caller of a coroutine sees it as an ordinary function call that synchronously returns a value of the declared type (here,
future<path>
). That value is but a placeholder, though: the function body executes only when that result is awaited—but not necessarilyco_await
ed, since the caller need not be a coroutine (the opacity again).Separately,
co_await
may suspend a coroutine, but need not do so (consider that it might be “waiting” on a coroutine with an empty function body). It’s also quite separate from calling the coroutine: one may writeto create the placeholder long before using it.