coroutine_管道(pipe)与过滤器(filter)

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值