Based on the current reactor code, adding simple scheduling capabilities and context preservation and restore capabilities should be able to implement the coroutine
The general idea is as follows:
1. The whole is divided into three types of coroutines,
1.1 The main coroutine,does not allocate an execution stack,
1.2 event_loop coroutine,execute event dispatch and call callback, need to allocate execution stack separately
1.3 Other coroutines,execute the function set by the user and need to allocate the execution stack separately
2. Each time an io operation is executed, the context of the current function is saved to an io queue, and a timeout callback and an io event ready callback are set. The callback logic is to move the coroutine to the runnable queue.
3. Every time the io operation is executed, go to the runnable queue to find the next coroutine context and switch to this context. If the next runnable coroutine is not found, then switch directly to the coroutine that executes event_loop, if there is an io event is ready, the corresponding callback function will be called back
4. Write coroutine version functions for commonly used io system calls
基于当前的 reactor 代码,在这上面增加简单的调度能力和上下文保存与 restore 能力应该就能实现协程
大致思路如下:
1. 整体分为三种协程,
1.1 主协程-不分配执行栈,
1.2 event_loop 协程-执行event dispatch 并调用回调,需要单独分配执行栈
1.3 其他协程-执行用户设定的 function,需要单独分配执行栈
2. 每次执行 io 操作时,将当前函数的上下文保存到一个 io 队列中,并设置一个超时回调和 io 事件 ready 回调,回调的逻辑是将协程移动到可运行队列。
3. 每次执行 io 操作时,去可运行队列中寻找下一个协程上下文,并切换到这个上下文,如果没有找到下一个可运行的协程,则直接切换到执行 event_loop 的协程,如果有 io 事件 ready,则会回调对应的回调函数
4. 为常用的 io 系统调用编写协程版本的函数