欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談chuck-lua中的多線(xiàn)程

 更新時(shí)間:2015年07月08日 11:34:57   投稿:hebedich  
Lua對(duì)多線(xiàn)程支持初步體驗(yàn)是本文要介紹的內(nèi)容,主要是來(lái)了解LUA中多線(xiàn)程的使用,,經(jīng)過(guò)反復(fù)的實(shí)驗(yàn)得到的結(jié)果是,lua不支持多線(xiàn)程,如何讓它支持?來(lái)看本文內(nèi)容。

chuck-lua支持actor模式的線(xiàn)程模型.可以通過(guò)cthread.new創(chuàng)建線(xiàn)程,然后通過(guò)cthread.sendmail向線(xiàn)程發(fā)送消息.

與skynet這種框架不同,chuck-lua并不提供多線(xiàn)程的任務(wù)/消息調(diào)度功能,每個(gè)線(xiàn)程維護(hù)了一個(gè)簡(jiǎn)單的線(xiàn)程郵箱,用于緩存其它線(xiàn)程發(fā)過(guò)來(lái)的消息.

下面看一個(gè)簡(jiǎn)單的多線(xiàn)程服務(wù)器示例:

mtserver.lua

local chuck = require("chuck")
local engine = require("distri.engine")
local socket_helper = chuck.socket_helper
local Distri = require("distri.distri")
local cthread = chuck.cthread

local worker 

function on_new_client(fd)
  cthread.sendmail(worker,{fd})
end

local fd = socket_helper.socket(socket_helper.AF_INET,
                 socket_helper.SOCK_STREAM,
                 socket_helper.IPPROTO_TCP)
socket_helper.addr_reuse(fd,1)

local ip = "127.0.0.1"
local port = 8010

if 0 == socket_helper.listen(fd,ip,port) then
  print("server start",ip,port)
  local server = chuck.acceptor(fd)
  server:Add2Engine(engine,on_new_client)
  Distri.Signal(chuck.signal.SIGINT,Distri.Stop) 
  worker = cthread.new("distri/test/worker.lua")
  Distri.Run()
end

worker.lua

local chuck = require("chuck")
local socket = require("distri.socket")
local engine = require("distri.engine")
local clone  = chuck.packet.clone
local cthread = chuck.cthread
local Distri = require("distri.distri")

--設(shè)置郵件處理函數(shù)
cthread.process_mail(engine,function (sender,mail)
  local fd = table.unpack(mail)
  local s = socket.stream.New(fd)
  if s:Ok(4096,socket.stream.decoder.rawpacket(),function (_,msg,errno)
    if msg then
      s:Send(clone(msg))
    else
      s:Close(errno)
      s = nil
    end
  end) then
    s:SetRecvTimeout(5000)
  else
    s:Close()
  end 
end)

Distri.Run()

這個(gè)示例很簡(jiǎn)單,主線(xiàn)程啟動(dòng)監(jiān)聽(tīng),創(chuàng)建一個(gè)線(xiàn)程,當(dāng)接收到連接時(shí)就將fd發(fā)送給worker線(xiàn)程.

在這里需要簡(jiǎn)單介紹一下chuck-lua線(xiàn)程相關(guān)的一些細(xì)節(jié).

因?yàn)楦骶€(xiàn)程跑在獨(dú)立的虛擬機(jī)上,因此無(wú)法直接通過(guò)消息的方式將一個(gè)虛擬機(jī)中的對(duì)象發(fā)送到另一個(gè)線(xiàn)程中.目前sendmail將作為消息傳遞給它的lua table序列化為一種適合傳輸?shù)膶?duì)象,目標(biāo)線(xiàn)程接收這個(gè)對(duì)象之后再重新轉(zhuǎn)化成本線(xiàn)程虛擬機(jī)中的lua table.目前消息支持lua中的所有基本類(lèi)型,但為了安全考慮,不支持直接傳遞userdata類(lèi)型.

用cthread.sendmail向目標(biāo)線(xiàn)程發(fā)送消息時(shí),如果到達(dá)目標(biāo)郵箱的緩沖上線(xiàn)將會(huì)阻塞.所有期望處理郵件消息的線(xiàn)程都必須調(diào)用cthread.process_mail設(shè)定消息回調(diào)函數(shù).如果不設(shè)定,將可能導(dǎo)致消息發(fā)送線(xiàn)程永久阻塞.

線(xiàn)程使用join模式創(chuàng)建,創(chuàng)建者可以通過(guò)cthread.join等待線(xiàn)程的結(jié)束.

以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。

相關(guān)文章

最新評(píng)論