Turi Create
4.0
|
Go to the source code of this file.
Very limited coroutine implementation.
Kind of inspired by https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
Essentially, DECL_CORO_STATE holds an integer which is a line number of the function., RESET_CORO resets that value to 0. CORO_YIELD sets the current line number so that the next time the function is called, a switch is used to jump to the next line.
Generally this means that this is not a truly general coroutine mechanic since it does not remember any stack state between function invocations. Any stack state has to be maintained outside the function. To some extent this is automatically checked by the compiler due to the use of switch statements. Generally extra braces between CORO_YIELDs might be necessary to get the compiler to accept the code.
Furthermore, parallel invocations, or multiple simultaneous coroutine invocations of the function is not allowed since there is a single global variable which maintains the line number. However, wrapping the DECL_CORO_STATE and the function in a struct/class will allow for it.
Example:
The behavior of this system is very subtle and takes some care to get right. A perculiarity is that argument values may be different between successive calls. Ex:
User must be careful to call the method with the same input arguments everytime or interesting behavior might happen. Similarly, this allows input arguments to be used to transfer information to the coroutine (for instance, in a producer/consumer model, an argument can be used to transfer a buffer from the consumer to the producer).
Example:
But some care must be taken because after a CORO_YIELD, any of the arguments may have new values. Essentially, CORO_YIELD itself is an entry point to the function and has to be treated that way.
To help in closure maintenance, a struct/class version of the macros are provided.
Definition in file coro.hpp.