目的:在lua文本中灵活创建多线程函数,类似如下效果(来源合宙Luat)。底层通过FreeRTOS去实现多线程。
-- 测试代码,用于发送消息给socket
sys.taskInit(
function()
while true do
sys.publish("pub_msg", "11223344556677889900AABBCCDDEEFF" .. os.time())
sys.wait(180000)
end
end
)
方法一:可在线程或者中断中查找并执行lua函数
函数如下,注意中断函数 SysTick_Handler 要在 _L 加载完毕后才调用。
//C程序
void SysTick_Handler()
{
if(lua_getglobal(_L,"_time_cllback"))//该函数被注册
{
lua_pushinteger(_L,clock());//传入参数
lua_pcall(_L, 1, 0, 0);//执行函数
}
}
--lua 程序
local ss = false
function _time_cllback(t)
if t % 50 == 0 then
--print(os.clock())
ss = not ss
if ss == true then
led.led_on()
else
led.led_off()
end
end
end
单纯上面的程序能正产运行,但是多线程的概念还没有。
在lua继续添加以下内容:
--lua 程序
local ss = false
function _time_cllback(t)
if t % 50 == 0 then
--print(os.clock())
ss = not ss
if ss == true then
led.led_on()
else
led.led_off()
end
end
end
while true do
for i = 1, 100000 do
end
print(os.clock())
end
运行lua文件后会出现如下错误:
*** assertion failed: (L->top <= L->ci->top) && "stack overflow", file ..\Lua\lapi.c, line 614
SIGABRT: Abnormal termination
看上去是堆栈溢出了!!!!!!
细想一下之前用FreeRTOS数据和堆栈都要考虑线程锁和中断锁,lua一些数据压栈的时候也得保护,压到一半就被中断打断了肯定不喝逻辑。所以可能是锁的问题,百度一波不是我想要的。再看看程序吧
本身lua库有提供锁的接口。但里面是空的未定义,简单通过开关中断实现锁。
/*
** macros that are executed whenever program enters the Lua core
** ('lua_lock') and leaves the core ('lua_unlock')
*/
#if !defined(lua_lock)
#define lua_lock(L) __disable_irq()// ((void) 0)
#define lua_unlock(L) __enable_irq() //((void) 0)
#endif
再运行没有报错。但是明显中断进去的次数变少了很多。led灯闪烁的很慢,lua中的wile循环正常。
其实这个现象也正常,中断的概念就是,不加锁的情况下,中断可以打断while并让中断程序执行。加入锁之后,中断只有在while释放锁的时间内得到执行。while占用了太多锁的时间,中断被执行的机会就大大缩短。
所以while主函数在执行完重要任务后要主动释放锁,让中断线程有机会执行。
修改lua中while程序如下:
while true do
--//for i = 1, 100000 do 长时间占用锁
--//end
os.sleep(100) --//加入非斥锁延时 期间中断可被响应
print(os.clock())
end
现在中断程序和主程序都能正常执行,不会出现错误。
但是 lua_getglobal(_L,"_time_cllback")需要c和lua同时规定函数名称_time_cllback,两者才能连通,使用起来很不灵活。
未能满足我开始提到的需求。
下一步继续研究。