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类型。