1. 程式人生 > >lua協程的使用列子分析

lua協程的使用列子分析

例子一

handle = coroutine.create(function (arg1,arge2)
  local start = 0

  print(arg1,arg2)

  while true do
    if( start == 0 or start == 20) then
      print("yield arg is :",coroutine.yield(arg .. "me",arg2+1))
      print("back to",start)
    end

    if start == 30 then
      break
    end

    start = start + 1
    print("it is first coroutine istance")
  end

  return "coroutine is over"

end)

print(coroutine.resume(handle,"test",1999))
print(coroutine.resume(handle,"ooo",33))
print(coroutine.resume(handle,"111",77))
print(coroutine.resume(handle,"jjj",55))


輸出結果:

分析

第一次呼叫resume,此時沒有對應的yield,它的引數時傳遞給匿名函式的

第二次呼叫resume,此時有對應的yield, 此時resume的作用是從函式yield返回,resume的引數正好傳遞給yield作為返回值(yield的第一個返回值是固定的,返回呼叫狀態true or false)

第一次呼叫yield,並傳遞了引數,此時的yield引數是作為:讓本次yield呼叫返回的(匿名函式繼續執行,而不是卡在yield函式呼叫處),resume 呼叫的返回值。

例子二(生產者,消費者)

function send(x)
  coroutine.yield(x)
end

pd_handle = coroutine.create(function ()
  local x = 0
  while true do
    x = io.read()
    send(x)
end)

fuction receive()
  local status,value = coroutine.resume(pd_handle)
  return value
end

function consumer()
  local y = 0
  while true do
    y = receive()
    print("receive value is :",y)
  end
end

consumer()