前言
之前写了个C++的协程框架,底层使用的是boost.context实现,然后剥离了对boost的依赖。然而这样意味着我必须时常跟进的更新。
顺带提一下这个协程库已经在我们线上服务器版本中使用了。
从最初的boost版本(我忘了从哪个版本开始了)一直到1.60版本,的变化都不大,都只是补全一些新的架构和体系结构,还有就是修复一些小细节的BUG,再就是增加了对valgrind的支持(之前写过一个提到过)。新增的功能也只有(现在叫execution_context_v1),这个东西我的里其实包含了这个功能,并且本身做得比它要功能丰富,所以没有接入的必要。另外在1.60版本的时候尝试使用Windows里的fiber(当然默认是关闭的),在1.61版本里被移除了。这些细节都不是特别重要,主要还是1.61版本的变化。
然而这次变化就比较大了,首先所有的API都变更了,汇编代码里的参数和返回值也都发生了变化,当然语义也不一样了,另外还增加了新的APIontop_fcontext。这些变化使得的逻辑关系也必须有一些相应的调整,为了理清思路,这些都在后面分析。
设计模型变化
API变化
先来看看原先的底层API
namespace boost {
namespace context {
/**
* @biref 执行环境上下文
*/
typedef void* fcontext_t;
/**
* @biref 跳转到目标上下文
* @param ofc 当前的上下文会保存到ofc中
* @param nfc 跳转到的目标上下文
* @param vp 如果是第一次跳转,作为函数参数传入,如果是调回到jump_fcontext,这个是返回值
* @param preserve_fpu 是否复制FPU(浮点数寄存器)数据
* @return 如果调回时的透传参数
*/
extern "C" BOOST_CONTEXT_DECL
intptr_t BOOST_CONTEXT_CALLDECL jump_fcontext( fcontext_t * ofc, fcontext_t nfc,
intptr_t vp, bool preserve_fpu = false);
/**
* @biref 初始化执行环境上下文
* @param sp 栈空间地址
* @param size 栈空间的大小
* @param fn 入口函数
* @return 返回初始化完成后的执行环境上下文
*/
extern "C" BOOST_CONTEXT_DECL
fcontext_t BOOST_CONTEXT_CALLDECL make_fcontext( void * sp, std::size_t size, void (* fn)( intptr_t) );
}}
然后是现在的API
namespace boost {
namespace context {
/**
* @biref 执行环境上下文
*/
typedef void* fcontext_t;
/**
* @biref 跳转到目标上下文
* @param ofc 当前的上下文会保存到ofc中
* @param nfc 跳转到的目标上下文
* @param vp 跳转到的目标上下文的附加参数。如果是第一次跳转,作为函数参数传入,如果是调回到jump_fcontext,这个是返回值
* @param preserve_fpu 是否复制FPU(浮点数寄存器)数据
* @return 如果调回时的透传参数
*/
extern "C" BOOST_CONTEXT_DECL
intptr_t BOOST_CONTEXT_CALLDECL jump_fcontext( fcontext_t * ofc, fcontext_t nfc,
intptr_t vp, bool preserve_fpu = false);
/**
* @biref 初始化执行环境上下文
* @param sp 栈空间地址
* @param size 栈空间的大小
* @param fn 入口函数
* @return 返回初始化完成后的执行环境上下文
*/
extern "C" BOOST_CONTEXT_DECL
fcontext_t BOOST_CONTEXT_CALLDECL make_fcontext( void * sp, std::size_t size, void (* fn)( intptr_t) );
}}
namespace boost {
namespace context {
namespace detail {
/**
* @biref 执行环境上下文
*/
typedef void* fcontext_t;
/**
* @biref 事件参数包装
*/
struct transfer_t {
fcontext_t fctx; /** 相关的的执行环境上下文-不同的API里含义不一样 **/
void * data; /** 自定义数据 **/
};
/**
* @biref 跳转到目标上下文
* @param to 当前的上下文会保存到ofc中
* @param vp 跳转到的目标上下文的附加参数,会设置为transfer_t里的data成员
* @return 跳转来源
*/
extern "C" BOOST_CONTEXT_DECL
transfer_t BOOST_CONTEXT_CALLDECL jump_fcontext( fcontext_t const to, void * vp);
/**
* @biref 初始化执行环境上下文
* @param sp 栈空间地址
* @param size 栈空间的大小
* @param fn 入口函数
* @return 返回初始化完成后的执行环境上下文
*/
extern "C" BOOST_CONTEXT_DECL
fcontext_t BOOST_CONTEXT_CALLDECL make_fcontext( void * sp, std::size_t size, void (* fn)( transfer_t) );
/**
* @biref 顶层跳转
* @param to 当前的上下文会保存到ofc中
* @param vp 跳转到的目标上下文的附加参数,会设置为transfer_t里的data成员
* @param fn 入口函数,参数是跳转来源
* @return 跳转来源
*/
// based on an idea of Giovanni Derreta
extern "C" BOOST_CONTEXT_DECL
transfer_t BOOST_CONTEXT_CALLDECL ontop_fcontext( fcontext_t const to, void * vp, transfer_t (* fn)( transfer_t) );
}}}
流程变化
诸如命名空间从boost转移到boost::detail这种废话我就不说了,这也是说作者不再希望用户直接使用这些接口了。然而这挡不住我非要直接用,哈哈。
重要的是首先API参数和返回值变化,对于这些接口变更,boost里并没有文档,也没有什么地方有说明,所以目前我只能通过它的单元测试和sample来评估功能。
首先重要的是多一个transfer_t,这个里面的有两个对象,第一个fctx是来源的执行上下文,第二个data是各种接口传入的自定义的指针(上面接口里的vp)。 来源的上下文指的是从什么位置跳转过来的。无论在回调参数还是各项返回值中都是这个含义。
对于make_fcontext这个接口,原先的入口函数是void ( fn)( intptr_t),参数是透传自定义指针。现在是void ( fn)( transfer_t),里面包含了来源执行栈的上下文和透传的自定义指针。
对于jump_fcontext这个接口,原先需要传入把当前执行上下文保存到哪里,跳转目标的新的上下文,自定义数据和是否复制FPU。 现在的版本不再需要指定是否需要复制FPU了,同时也去除了自动保存当前上下文的功能,并且改成了跳到新的上下文后,新的上下文可以知道自己是从哪跳转过来的。
// Step 1. 当前处于执行上下文-fctx1
transfer_t jump_res = jump_fcontext(fctx2, NULL);
// ...
// Step 2. 当前处于执行上下文-fctx2
// 跳入ontop_callback函数
ontop_fcontext(fctx1, 0x01, ontop_callback);
transfer_t ontop_callback( transfer_t from) {
// 这时候 from.fctx == fctx2, from.data == 0x01
// Step 3. 可以改变这些数据
from.data = 0x02;
return from;
}
// 这时候返回Step 1的
transfer_t jump_res = jump_fcontext(fctx2, NULL);
// Step 4. 这时候,jump_res.fctx == fctx2, from.data == 0x02
// continue other ...
向前兼容
struct data_t {
activation_record * from;
void * data;
};
那么jump_fcontext和ontop_fcontext的vp参数都是data_t*,然后每次跳入后保存调用来源的上下文
// ========== 调用jump_fcontext ==========
// store current activation record in local variable
auto from = current_rec.get(); // 这是一个TLS变量记录当前执行环境上下文
// store `this` in static, thread local pointer
// `this` will become the active (running) context
// returned by execution_context::current()
current_rec = this; // 更新当前执行环境上下文
// 这一段是对GCC动态栈的支持
#if defined(BOOST_USE_SEGMENTED_STACKS)
// adjust segmented stack properties
__splitstack_getcontext( from->sctx.segments_ctx);
__splitstack_setcontext( sctx.segments_ctx);
#endif
data_t d = { from, vp }; // vp 是外部传入的private data
// context switch from parent context to `this`-context
transfer_t t = jump_fcontext( fctx, & d);
data_t * dp = reinterpret_cast< data_t * >( t.data);
dp->from->fctx = t.fctx; // 保存来源上下文
// ========== 通过jump_fcontext第一次跳入 ==========
// tampoline function
// entered if the execution context
// is resumed for the first time
template< typename AR >
static void entry_func( detail::transfer_t t) noexcept {
detail::data_t * dp = reinterpret_cast< detail::data_t * >( t.data);
AR * ar = static_cast< AR * >( dp->data);
BOOST_ASSERT( nullptr != ar);
dp->from->fctx = t.fctx; // 保存来源上下文
// start execution of toplevel context-function
ar->run();
}
// ========== 调用ontop_fcontext ==========
std::tuple< void *, Fn > p = std::forward_as_tuple( data, fn);
data_t d = { from, & p };
// context switch from parent context to `this`-context
// execute Fn( Tpl) on top of `this`
transfer_t t = ontop_fcontext( fctx, & d, context_ontop< Fn >);
data_t * dp = reinterpret_cast< data_t * >( t.data);
dp->from->fctx = t.fctx; // 保存来源上下文
// ========== 通过ontop_fcontext跳入 ==========
template< typename Fn >
transfer_t context_ontop( transfer_t t) {
data_t * dp = reinterpret_cast< data_t * >( t.data);
dp->from->fctx = t.fctx; // 保存来源上下文
auto tpl = reinterpret_cast< std::tuple< void *, Fn > * >( dp->data);
BOOST_ASSERT( nullptr != tpl);
auto data = std::get< 0 >( * tpl);
typename std::decay< Fn >::type fn = std::forward< Fn >( std::get< 1 >( * tpl) );
dp->data = apply( fn, std::tie( data) );
return { t.fctx, dp };
}
execution_context_v2
/** 参数包装 **/
typedef std::tuple< Args ... > args_tpl_t;
/** 返回值包装 **/
typedef std::tuple< execution_context, typename std::decay< Args >::type ... > ret_tpl_t;
/** 用于记录栈地址,入口函数和参数的对象 **/
typedef record< Ctx, StackAlloc, Fn, Params ... > record_t;
// ========== 调用jump_fcontext - context_create函数内 ==========
// create fast-context
const fcontext_t fctx = make_fcontext( sp, size, & context_entry< record_t >);
BOOST_ASSERT( nullptr != fctx);
// placment new for control structure on context-stack
auto rec = ::new ( sp) record_t{
sctx, salloc, std::forward< Fn >( fn), std::forward< Params >( params) ... };
// transfer control structure to context-stack
return jump_fcontext( fctx, rec).fctx;
// ========== 调用jump_fcontext - ret_tpl_t operator()( Args ... args)函数内 ==========
ret_tpl_t operator()( Args ... args) {
BOOST_ASSERT( nullptr != fctx_);
args_tpl_t data( std::forward< Args >( args) ... );
detail::transfer_t t = detail::jump_fcontext( detail::exchange( fctx_, nullptr), & data);
if ( nullptr != t.data) {
data = std::move( * static_cast< args_tpl_t * >( t.data) );
}
return std::tuple_cat( std::forward_as_tuple( execution_context( t.fctx) ), std::move( data) );
}
// ========== 通过jump_fcontext第一次跳入 ==========
template< typename Rec >
void context_entry( transfer_t t_) noexcept {
// transfer control structure to the context-stack
Rec * rec = static_cast< Rec * >( t_.data);
BOOST_ASSERT( nullptr != rec);
transfer_t t = { nullptr, nullptr };
try {
// jump back to `context_create()`
t = jump_fcontext( t_.fctx, nullptr);
// start executing
t = rec->run( t);
} catch ( forced_unwind const& e) {
t = { e.fctx, nullptr };
}
BOOST_ASSERT( nullptr != t.fctx);
// destroy context-stack of `this`context on next context
ontop_fcontext( t.fctx, rec, context_exit< Rec >);
BOOST_ASSERT_MSG( false, "context already terminated");
}
// ========== 调用ontop_fcontext ==========
template< typename Fn >
ret_tpl_t operator()( exec_ontop_arg_t, Fn && fn, Args ... args) {
BOOST_ASSERT( nullptr != fctx_);
args_tpl_t data{ std::forward< Args >( args) ... };
auto p = std::make_tuple( fn, std::move( data) ); // 透传类型是 std::tuple<Fn, args_tpl_t>
detail::transfer_t t = detail::ontop_fcontext(
detail::exchange( fctx_, nullptr), // 跳入fctx_并把fctx_置空
& p,
detail::context_ontop< execution_context, Fn, Args ... >);
if ( nullptr != t.data) {
data = std::move( * static_cast< args_tpl_t * >( t.data) );
}
return std::tuple_cat( std::forward_as_tuple( execution_context( t.fctx) ), std::move( data) );
}
// ========== 通过ontop_fcontext跳入 ==========
template< typename Ctx, typename Fn, typename ... Args >
transfer_t context_ontop( transfer_t t) {
auto tpl = static_cast< std::tuple< Fn, std::tuple< Args ... > > * >( t.data);
BOOST_ASSERT( nullptr != tpl);
typename std::decay< Fn >::type fn = std::forward< Fn >( std::get< 0 >( * tpl) );
auto args = std::move( std::get< 1 >( * tpl) );
Ctx ctx{ t.fctx };
// execute function
auto result = apply( // apply的作用是展开并调用fn函数: fn(ctx, unpack(args))
fn,
std::tuple_cat(
std::forward_as_tuple( std::move( ctx) ),
std::move( args) ) );
ctx = std::move( std::get< 0 >( result) );
// apply returned data
detail::tail( args) = std::move( result);
std::get< 1 >( * tpl) = std::move( args);
return { exchange( ctx.fctx_, nullptr), & std::get< 1 >( * tpl) };
}
存在的问题
其他不是很重要的变化
很多函数重新整理了一下,增加了noexpect/nothrow等。
libcopp的修订
这次的merge,使用新的设计模型是必然的,但与此同时,我也会做一些细节的优化和调整。主要是下面几大块:
优化 原来使用spin lock来处理多线程保护,还是抽象出跨平台且比较简单的原子操作类吧。好多时候想用但是因为麻烦直接用了c++11的atomic,但是这货gcc 4.4里没有。
更新 接入新API的话,跳转来源只能靠this_coroutine提供了。原先是对多线程且不支持TLS的环境不能使用this_coroutine,现在基础功能依赖它的话就必须保证其正确。那么计划是VC的话还是必须使用高版本(反正有社区版免费),GCC/Clang之流使用pthread处理TLS吧。
优化 coroutine增加private data,然后this_task可以用this_coroutine关联,不需要两个TLS变量了,这是之前设计的一处小失误。这样task的多线程重入也可以用coroutine的。
更新 caller应该要变为每次入口函数后初始化和不是来自yield的jump_to后更新。基本上caller只需要记录fcontext(支持GCC动态栈的情况下还需要多复制一个动态执行栈的数据),作用也只有执行完成后跳回。如果不是调用yield导致返回的,则是外部主动调用resume,所以结束时也需要返回到主动调用的地方。
更新 start内的jump_to只能通过this_XXX来获取来源协程,yield内的jump_to的来源就是this。每次jump_to返回后都要更新来源协程的callee
更新 this_XXX功能应该是入口函数处设置和jump_to执行返回后刷新(不能由外层记录old,因为可能发生变化)。起新的协程和yield都会走jump_to,同样start内得设为jump_to前的this_XXX,而yield的直接设为this
预计重构完成后性能不会有太大的改变,甚至因为更多地使用原子操作,可能导致性能还会变低一些。不过毕竟实际运用中并不需要经常做协程切换操作,而且逻辑的复杂度源超协程切换,所以关系不大。 但是重构完后使用者更不容易出现错误,并且可以支持协程A跳转到协程B再跳转到协程A这种循环跳转,还是值得的。具体由多大变化,还是等重构完后看测试结果吧。