Lua编程示例(八):生产者-消费者问题
技术  /  管理员 发布于 5年前   372
这个问题是比较经典的啦,基本所有语言的多线程都会涉及到,但是没想到Lua的这个这么复杂 抓狂
看了好长时间才算看明白,先上个逻辑图:
开始时调用消费者,当消费者需要值时,再调用生产者生产值,生产者生产值后停止,直到消费者再次请求。设计为消费者驱动的设计。
图画的不太好,可以先将Filter遮住,它是过滤器对两个程序之间传递的信息进行处理。去掉Filter逻辑就更清晰些了,就是两个“线程”(其实是两个协同程序)互相调用。resume回到yield处开始,支持嵌套,返回到栈顶的yield位置。yield是非阻塞的“线程同步”。这到有点像linux里的管道通信。
function receive(prod) print("receive is called") local status,value = coroutine.resume(prod) return valueendfunction send(x,prod) print("send is called") return coroutine.yield(x)endfunction producer() return coroutine.create(function () print("producer is called") while true do print("producer run again") local x = io.read() send(x) end end)endfunction 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)endfunction consumer(prod) print("consumer is called") while true do print("consumer run again") local x = receive(prod) print("retrun customer") io.write(x,"\n") endendp = producer()f=filter(p)consumer(f)
运行结果:
consumer is calledconsumer run againreceive is calledenter fliter 1receive is calledproducer is calledproducer run againfsysend is calledreceive in filter finishedsend is calledretrun customer 1 fsyconsumer run againreceive is calledenter fliter 2receive is calledproducer run againgagasend is calledreceive in filter finishedsend is calledretrun customer 2 gagaconsumer run againreceive is calledenter fliter 3receive is calledproducer run again......
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号