Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does co_await operator actually do?

I have searched the Internet trying to find what does the co_await operator do, but I still can't understand that. I guess that the following code:

co_await foo();

suspends the coroutine until foo is done, but in this case how it differs from simply calling foo like:

foo();

This will also suspend the current function until foo is done. Please, explain me.

like image 759
Count Zero Avatar asked Jun 20 '18 18:06

Count Zero


1 Answers

If function contains at least one co_await operator, the whole function is considered to be a coroutine. All its scope variables (including parameters) are stored on the heap, not on the stack. This makes it possible to suspend the function execution without losing its state and resume when needed. Also the coroutine returns control to the caller on the first suspend, and completes on the first return statement. Since it returns uncompleted, the return type must be an "awaitable type", such as std::future<int>. (C++ allows you to create your own awaitable types - and it's awesome!) The caller can subscribe/co_await on function completion.

Important to note that the suspended function may resume and complete at any time and on any thread; details depend on the implementation.

In your example, when you write co_await foo(), you will get to the next line only after foo completed execution and this line may be executed in another thread, however writing foo(), will get to the next line when foo() is only suspended in the same thread, and you won't have any feedback about its completion.

like image 113
jenkas Avatar answered Oct 20 '22 08:10

jenkas