關鍵點是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()