這個問題是比較經典的啦,基本所有語言的多線程都會涉及到,但是沒想到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......
新聞熱點
疑難解答