LuaJIT的coroutine兼容性问题

LuaJIT的coroutine兼容性问题

//
// 这个测试说明Lua和LuaJIT在协程的处理能力上有所不同,
// LuaJIT在处理从Lua yield到Lua的操作方面缺乏兼容性,
// 但是,CoCo附带的例子: cotet.lua 说明,由于LuaJIT有CoCo的支持,
// 在Lua测 pcall 的支持得到了加强.
//

bool test_c_lua_coroutine()
{
//
// not passed in LuaJIT
//
LuaStateInCpp* state=new LuaStateInCpp();
state->init(NULL);
state->do_string("a=function() i=coroutine.yield(1);print(i);coroutine.yield(2);end");
LuaStateInCpp* co=state->new_thread("a");
printf("start...n");
int yieldret=co->resume();
printf("n first yield ret = %d",yieldret);
yieldret=co->resume();
printf("n 2nd yield ret = %d",yieldret);
yieldret=co->resume();
printf("n 3rd yield ret = %d",yieldret);

//
// passed in LuaJIT
//
{
LuaStateInCpp* state=new LuaStateInCpp();
state->init(NULL);
state->do_string("a=function() i=coroutine.yield(1);print(i);coroutine.yield(2);end");
state->do_string("co=coroutine.wrap(a)");
state->do_string("print('1: '..co())");
state->do_string("print('2: '..co())");
state->do_string("print('3: '..(co() or ''))");
}

return true;
}




Lua 5.1.2 Copyright (C) 1994-2007 Lua.org, PUC-Rio
> require "linker_mod"
linker_mod ver:1.0.0.0 loaded!
> test_c_lua_coroutine()
cannot open : Invalid argumentstart...

first yield ret = 1nil

2nd yield ret = 1
3rd yield ret = 0cannot open : Invalid argument1: 1
nil
2: 2
3:





Lua 5.1.3 Copyright (C) 1994-2008 Lua.org, PUC-Rio
LuaJIT 1.1.4 Copyright (C) 2005-2008 Mike Pall, http://luajit.org/
> require"linker_mod"
linker_mod ver:1.0.0.0 loaded!
> test_c_lua_coroutine()
cannot open : Invalid argumentstart...
attempt to yield across metamethod/C-call boundary
first yield ret = -1cannot resume non-suspended coroutine
2nd yield ret = -1cannot resume non-suspended coroutine
3rd yield ret = -1cannot open : Invalid argument1: 1
nil
2: 2
3:
>


为了解决这个问题,有人在Lua WiKi上写过一个 patch. 但是这个patch是没有经过充分测试和验证的.
并长期没有维护.
简单来说,导致LuaVM存在yield resume问题的根源是c函数的上下文和lua协程的上下文的对应关系的处理上.
其实彻底的解决方法就是避免在C和Lua之间直接进行协程的切换.而是在Lua侧进行全部的协程切换工作.对C的使用
仅限于简单的函数调用.
这样就可以避免很多问题.













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值