Lua编程示例(八):生产者-消费者问题

时间:2021-05-22

这个问题是比较经典的啦,基本所有语言的多线程都会涉及到,但是没想到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......

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章