一种在C语言中用汇编指令和 System V ucontext 支撑实现的协程切换
1 实现内容 此文在看了 python yield 和 yield from 机制后,觉得 这种轻量级编程技术在小并发场景下优雅可爱,在大并发场景下较进程或线程而言能突破资源瓶颈 ,实在令人忍不住而想在C语言中实现一个。 然后经过一些学习后,此文就在 Linux 上用C语言实现了一个。目前具体包括 [1] co_yield() —— 类似 python 的 yield,用于协程切换; [2] co_send() —— 类似 python 生成器中的 send(),用于开始或恢复协程的执行; [3] co_yield_from() —— 类似 python 的 yield from,用于同步基于 co_yield() 切换的协程; [4] co_loop() —— 略似于 python 的 asyncio.loop(),用于协程并发调度。 e.g. /** ** brief: suspending current coroutine related with ci then switch to specific coroutine when co_yield() called. ** param: ci, bears control-information for corresponding coroutine. ** return: zero returned if