主頁 > 知識(shí)庫 > Lua編程示例(八):生產(chǎn)者-消費(fèi)者問題

Lua編程示例(八):生產(chǎn)者-消費(fèi)者問題

熱門標(biāo)簽:艾比利外呼系統(tǒng) 衡水外呼線路解決 昆明電話外呼系統(tǒng)好么 ??谥悄苷Z音電銷機(jī)器人好用嗎 免費(fèi)門店地圖標(biāo)注注冊入駐 杞縣地圖標(biāo)注app 電話機(jī)器人每天搜索多少次 陜西便宜電銷機(jī)器人軟件 外呼系統(tǒng)一天耗費(fèi)多少流量

這個(gè)問題是比較經(jīng)典的啦,基本所有語言的多線程都會(huì)涉及到,但是沒想到Lua的這個(gè)這么復(fù)雜 抓狂
  看了好長時(shí)間才算看明白,先上個(gè)邏輯圖:

   開始時(shí)調(diào)用消費(fèi)者,當(dāng)消費(fèi)者需要值時(shí),再調(diào)用生產(chǎn)者生產(chǎn)值,生產(chǎn)者生產(chǎn)值后停止,直到消費(fèi)者再次請求。設(shè)計(jì)為消費(fèi)者驅(qū)動(dòng)的設(shè)計(jì)。
   圖畫的不太好,可以先將Filter遮住,它是過濾器對(duì)兩個(gè)程序之間傳遞的信息進(jìn)行處理。去掉Filter邏輯就更清晰些了,就是兩個(gè)“線程”(其實(shí)是兩個(gè)協(xié)同程序)互相調(diào)用。resume回到y(tǒng)ield處開始,支持嵌套,返回到棧頂?shù)膟ield位置。yield是非阻塞的“線程同步”。這到有點(diǎn)像linux里的管道通信。


 

 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)


運(yùn)行結(jié)果:

consumer is called
consumer run again
receive is called
enter fliter 1
receive is called
producer is called
producer run again
fsy
send is called
receive in filter finished
send is called
retrun customer
  1 fsy
consumer run again
receive is called
enter fliter 2
receive is called
producer run again
gaga
send is called
receive in filter finished
send is called
retrun customer
  2 gaga
consumer run again
receive is called
enter fliter 3
receive is called
producer run again
......

您可能感興趣的文章:
  • Lua編程示例(一):select、debug、可變參數(shù)、table操作、error
  • Lua編程示例(二):面向?qū)ο?、metatable對(duì)表進(jìn)行擴(kuò)展
  • Lua編程示例(三):稀疏表、雙端隊(duì)列、格式化輸出、表和循環(huán)表的格式化輸出
  • Lua編程示例(四):Lua標(biāo)準(zhǔn)庫之表庫、字符串庫、系統(tǒng)庫
  • Lua編程示例(五): C語言對(duì)Lua表的讀取和添加
  • Lua編程示例(六): C語言調(diào)用Lua函數(shù)
  • Lua編程示例(七):協(xié)同程序基礎(chǔ)邏輯

標(biāo)簽:臨滄 宿遷 西寧 昌都 泰安 營口 南京

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Lua編程示例(八):生產(chǎn)者-消費(fèi)者問題》,本文關(guān)鍵詞  Lua,編程,示例,八,生產(chǎn)者,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Lua編程示例(八):生產(chǎn)者-消費(fèi)者問題》相關(guān)的同類信息!
  • 本頁收集關(guān)于Lua編程示例(八):生產(chǎn)者-消費(fèi)者問題的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章