1.协同程序是一种匹配生产者和消费者的理想工具
producer=coroutine.create(function() –生产者
while true do
local x=io.read()
send(x)
end
end)
function consumer()–消费者while true do
local x=receive()
io.write(x,”\n”)
end
end
function receive()local status,value=coroutine.resume(producer)
return value
end
function send(x)coroutine.yield(x)
end
consumer()–通过消费者启动,消费者需要时唤醒生产者,这种方式称为消费者驱动
2.管道和过滤器
function receive(produce)
local status,value=coroutine.resume(produce)
return value
end
function send(x)
coroutine.yield(x)
end
function producer()
return coroutine.create(function()
while true do
local x=io.read()
send(x)
end
end)
end
function filter(produce)
return coroutine.create(function()
for line=1,math.huge do
local x=receive(produce)—-获取新值
x=string.format(“%d %s”,line,x)–进行格式化处理 过滤
send(x)—将新值发送给消费者
end
end)
end
function consumer(produce)
while true do
local x=receive(produce)
io.write(x,”\n”)
end
end
p=producer()
f=filter(p)
consumer(f)