The co_await Keyword
Understand the use of the 'co_await' keyword in C++20.
We'll cover the following...
co_await
eventually causes the execution of the coroutine to be suspended or resumed. The expression exp
in co_await exp
has to be a so-called awaitable expression, i.e. which must implement a specific interface, consisting of the three functions await_ready
, await_suspend
, and await_resume
.
A typical use case for co_await
is a server that waits for events.
Acceptor acceptor{443}while (true) {Socket socket = acceptor.accept(); // blockingauto request = socket.read(); // blockingauto response = handleRequest(request);socket.write(response); // blocking}
The server is quite simple because it sequentially answers each request in the same thread. The server listens on port (line 1), accepts the connection (line 3), reads the incoming data from the client (line 4), and writes its answer to the client (line 6). The calls in lines 3, 4, and 6 are blocking.
Thanks to co_await
, the blocking calls can now be suspended and resumed.
Acceptor acceptor{443}while (true) {Socket socket = co_await acceptor.accept();auto request = co_await socket.read();auto response = handleRequest(request);co_await socket.write(response);}
Before I present the challenging example of thread synchronization with coroutines, I want to start with something straightforward: starting a job on request.