国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

Lua編程示例(八):生產者-消費者問題

2024-07-21 23:05:00
字體:
來源:轉載
供稿:網友

這個問題是比較經典的啦,基本所有語言的多線程都會涉及到,但是沒想到Lua的這個這么復雜 抓狂
  看了好長時間才算看明白,先上個邏輯圖:

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......

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建平县| 淳化县| 临江市| 浙江省| 青海省| 穆棱市| 湾仔区| 兴安县| 读书| 抚顺市| 黄平县| 高雄市| 任丘市| 丰镇市| 达拉特旗| 温泉县| 石阡县| 鄢陵县| 靖宇县| 柳州市| 衡水市| 尼勒克县| 南平市| 宝清县| 万盛区| 武川县| 兰考县| 萨嘎县| 恭城| 潞西市| 鄂托克前旗| 扶绥县| 寿光市| 莱州市| 莎车县| 涿州市| 永城市| 枣阳市| 昌江| 越西县| 宁武县|