2014-12-31 wcdj
Linux POSIXcoroutine初步
目录
摘要:开发同学在设计高性能后台服务时会优先考虑异步的执行方式,而目前异步执行方式主要有基于事件驱动的状态机模型、coroutine协程模型、Future/Promise模型。很多现代编程语言都提供了原生的coroutine特性(同步代码,异步执行)。本文总结下Linux使用POSIXsetcontext系列调用以实现coroutine语义的方法。
1 背景介绍
在代码里使用context需要包含ucontext.h(/usr/include/ucontext.h)系统头文件。
此头文件列出了POSIX下关于context operation的interface。并且可以看到此头文件还会引用另一个头文件/usr/include/sys/ucontext.h。
补充说明:
(1) setcontext function transfers controlto the context in ucp. Execution continues from the point at which the contextwas stored in ucp. setcontext does not return.
(2) getcontext saves current context intoucp. This function returns in two possible cases: after the initial call, orwhen a thread switches to the context in ucp via setcontext or swapcontext. Thegetcontext function does not provide a return value to distinguish the cases(its return value is used solely to signal error), so the programmer must usean explicit flag variable, which must not be a register variable and must bedeclared volatile to avoid constant propagation or other compiler optimizations.
(3) makecontext function sets up analternate thread of control in ucp, which has previously been initialized usinggetcontext. The ucp.uc_stack member should be pointed to an appropriately sizedstack; the constant SIGSTKSZ is commonly used. When ucp is jumped to usingsetcontext or swapcontext, execution will begin at the entry point to thefunction pointed to bye func, with argc arguments as specified. When functerminates, control is returned to ucp.uc_link.
(4) swapcontext transfers control to ucpand saves the current execution state into oucp.
头文件/usr/include/sys/ucontext.h主要是定义了相关的Register和DS,用户需要关心的是Userlevel context的ucontext_t类型。

本文探讨了在Linux环境下使用POSIX的setcontext等函数实现协程(coroutine)的方法。介绍了相关函数的作用,如setcontext用于转移控制权,getcontext用于保存当前上下文,makecontext用于设置新的执行线程,swapcontext则在上下文间切换。通过代码实践展示了具体实现过程,包括coroutine的创建、切换和调试信息。
最低0.47元/天 解锁文章
955

被折叠的 条评论
为什么被折叠?



