-
调用 p r o d u c e r ( ) producer() producer() 返回一个 c o r o u t i n e coroutine coroutine
-
调用 f i l t e r ( p r o d ) filter(prod) filter(prod) 返回一个 c o r o u t i n e coroutine coroutine
-
执行 c o n s u m e r ( p r o d ) consumer(prod) consumer(prod) 函数
- c o n s u m e r consumer consumer 调用 r e c e i v e receive receive 函数
- f i l t e r filter filter 协程开始执行
- p r o d u c e r producer producer 协程开始执行
- s e n d send send, p r o d u c e r producer producer 协程挂起
- f i l t e r filter filter 协程挂起
- 返回到 c o n s u m e r consumer consumer 的 r e c e i v e receive receive 函数
实现
#!/usr/local/bin/lua
function send(x)
coroutine.yield(x)
end
--[[
-- 生产者
-- 创建一个coroutine,生产、停止生产、发送商品
--]]
function producer()
return coroutine.create(function()
while true do
local x = io.read() -- 生产商品
send(x) -- 停止生产、返回商品
end
end)
end
function receive(prod)
local status, value = coroutine.resume(prod)
return value
end
function filter(prod)
return coroutine.create(function()
for line = 1, math.huge do
local x = receive(prod)
x = string.format("%5d %s", line, x)
send(x)
end
end)
end
--[[
-- 消费者一直循环,当需要消费就唤醒生产者
--]]
function consumer(prod)
while true do
local x = receive(prod) -- filter coroutine
io.write(x, "\n")
end
end
consumer(filter(producer()))
输出
lua
1 lua
c++
2 c++
py
3 py
结语
Lua还在精进中,期待您的关注~~