Linux POSIX coroutine初步

本文探讨了在Linux环境下使用POSIX的setcontext等函数实现协程(coroutine)的方法。介绍了相关函数的作用,如setcontext用于转移控制权,getcontext用于保存当前上下文,makecontext用于设置新的执行线程,swapcontext则在上下文间切换。通过代码实践展示了具体实现过程,包括coroutine的创建、切换和调试信息。
摘要由CSDN通过智能技术生成

2014-12-31 wcdj


Linux POSIXcoroutine初步

目录

1 背景介绍...1

2 代码实践...4

 

 

摘要:开发同学在设计高性能后台服务时会优先考虑异步的执行方式,而目前异步执行方式主要有基于事件驱动的状态机模型、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类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值