lua同步调用C异步函数

时间:2014-12-28 14:06:50

标签: c asynchronous lua

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(),利用网络recv数据并调用lua_resume())

return lua_yieldk(L, 0, 0, yield_continue);

它运行到yield_continue函数,但没有运行到"[run here]"行,为什么?

参考网址:http://www.lua.org/manual/5.2/manual.html#4.7

1 个答案:

答案 0 :(得分:0)

这是调度员的主要想法。

工作线程启动异步操作并切换到调度程序线程。 Dispatcher线程轮询异步操作以及何时切换到 工人线程。

-- 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()