lua語言生產者,消費者

關鍵點是yield和resume互相返回爲參數

local newProductor

function productor()
     local i = 0
     while true do
          i = i + 1
          send(i)     -- 將生產的物品發送給消費者
     end
end

function consumer()
     while true do
          local i = receive()     -- 從生產者那裏得到物品
          print(i)
     end
end

function receive()
     local status, value = coroutine.resume(newProductor)
     return value
end

function send(x)
     coroutine.yield(x)     -- x表示需要發送的值,值返回以後,就掛起該協同程序
end

-- 啓動程序
newProductor = coroutine.create(productor)
consumer()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章