Lua编程示例(八):生产者-消费者问题(编程实现生产者消费者模式)速看

随心笔谈2年前发布 编辑
146 0
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买


function receive(prod)
print(“receive is called”)
local status,value=coroutine.resume(prod)
return value
end

function send(x,prod)
print(“send is called”)
return coroutine.yield(x)
end

function producer()
return coroutine.create(function ()
print(“producer is called”)
while true do
print(“producer run again”)
local x=io.read()
send(x)
end
end)
end

function filter(prod)
return coroutine.create(function ()
for line=1,1000 do
print(“enter fliter “..line)
local x=receive(prod)
print(“receive in filter finished”)
x=string.format(“%5d %s”,line,x)
send(x,prod)
end
end)
end

function consumer(prod)
print(“consumer is called”)
while true do
print(“consumer run again”)
local x=receive(prod)
print(“retrun customer”)
io.write(x,”\n”)
end
end

p=producer()
f=filter(p)
consumer(f)

© 版权声明

相关文章