代码及注释如下,使用print函数打印值和行号,可以看到代码的运行路径
--[[
resume协程,如果协程执行的过程中调用yield函数,则resume函数返回yield的参数
]]
function receive(prod)
local status, value = coroutine.resume(prod)
print(value, debug.getinfo(1).currentline)
return value
end
--[[
若是在一个协程里调用yield函数,则会挂起当前协程
]]
function send(x)
print(x, debug.getinfo(1).currentline)
coroutine.yield(x)
end
--[[
创建一个协程,生产、停止生产、将生产的东西发给消费者
]]
function producer()
return coroutine.create(function ()
while true do
local x = io.read() -- 生产商品
print(x, debug.getinfo(1).currentline)
send(x) --停止生产、返回商品
end
end)
end
--[[
消费者是一个循环,当需要消费的时候,就唤醒生产者
然后将商品打印出来
]]
function consumer(prod)
while true do
local x = receive(prod) -- 参数是filter协程
print(x, debug.getinfo(1).currentline)
io.write(x, "\n")
end
end
function filter(prod)
return coroutine.create(function ()
local line = 1
while true do
local x &#