Flow control
Capy’s design is driven by the needs of network I/O processing. A piece of the program often has to wait for an I/O operation to finish before it can continue. Nobody can predict when that happens. Capy’s design pursues three goals:
-
To use this waiting time as efficiently as possible, processing other tasks.
-
To avoid any concurrency or lifetime management bugs.
-
To have the user code be simple and intuitive.
To achieve this, Capy uses the proactor pattern hidden behind the coroutine co_await mechanism.
In the proactor pattern, the program starts an operation and receives a notification when the operation completes.
When the user needs the result of an I/O operation, they:
-
Start the I/O operation.
-
Register a piece of code to be invoked when the I/O operation finishes.
-
Return control, so that other tasks can make progress.
This is exactly what happens when you write:
auto [ec, n] = co_await stream.read_some(buffer);
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ (1)
if (!ec)
process(buffer, n);
/*~~~~~~~~~~~~~~~~*/ (2)
| 1 | The co_await-expression starts the I/O operation,
and registers the resumption of the coroutine through its
executor.
Once the operation starts and the resumption is registered,
the coroutine suspends, and the program thread switches to performing other tasks. |
| 2 | When the I/O operation finishes, the executor resumes the coroutine.
Execution continues with the statement that follows the co_await-expression,
which checks the error code before it uses the result. |
While all this registering happens hidden in the coroutine mechanism, the coroutine body reads as sequential business logic.