c用以下代码调用lua
if ( lua_pcallk(L, 0, LUA_MULTRET, 0, ctx, pcallk_continue) != 0 )
{}
lua代码是
local coroutine = coroutine
co = coroutine.create( function (...)
c.call(...)
-- [run here]
end )
c.call()
是一个异步C函数(在函数末尾调用lua_yieldk(),利用网络接收数据并调用lua_resume())
return lua_yieldk(L, 0, 0, yield_continue);
它可以运行yield_continue
,但不能运行到,这是"[run here]"
为什么?
这是调度员的主要思想。
工作线程启动异步操作并切换到调度程序线程。分派器线程轮询异步操作,并在完成操作时切换到辅助线程。
-- basic async operation queue
local ASYNC_RECV = {}
-- Put operation to queue and wait
local function recv()
local co = coroutine.running()
-- here we start async operation
ASYNC_RECV[co] = true
-- here we switch to dispatcher
return coroutine.yield()
end
coroutine.wrap(function()
for i = 1, 10 do print(recv()) end
end)()
-- main Loop
-- here we poll all async operation and
-- resume according coroutines
while true do
-- we have no async operation
if not next(ASYNC_RECV) then break end
for co in pairs(ASYNC_RECV) do
ASYNC_RECV[co] = nil -- mark operation is done
coroutine.resume(co, "some string") -- send result to coroutine
end
end
这是使用libuv作为调度程序的工作示例
local uv = require "lluv"
local function sleep(timeout)
local co = coroutine.running()
-- here we start async operation
uv.timer():start(timeout, function(timer)
timer:close() -- just close unused timer.
-- dispatcher(libuv) call this callback and
-- callback switch to coroutine
coroutine.resume(co)
end)
coroutine.yield()
end
coroutine.wrap(function()
for i = 1, 10 do
print("Tick")
sleep(1000)
end
end)()
uv.run()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句