resty thread

local t = {}

local function produce_thread()
  for i=1,5 do
    t[i] = i
    ngx.say("produce:",i)
    ngx.sleep(0.01)
  end
end

local function consume_thread()
  for i=1,5 do
    for k,v in pairs(t) do
      if t[k] ~= 0 then
        ngx.say("consume:",t[k])        
        t[k] = 0
      end          
    end
    ngx.sleep(0.03)
  end
end

 local tp, err = ngx.thread.spawn(produce_thread)
 if not tp then
     ngx.say("failed to create produce thread: ", err)
     return
 end
 
 local tc, err = ngx.thread.spawn(consume_thread)
 if not tc then
     ngx.say("failed to create consume thread: ", err)
     return
 end                              
 
 local ok, res = ngx.thread.wait(tp, tc)
 if not ok then
     ngx.say("failed to wait: ", res)
     return
 end               

produce:1
consume:1
produce:2
produce:3
consume:2
consume:3
produce:4
produce:5
consume:4
consume:5                                                                                                                                                                                                                                                                                                                                            

猜你喜欢

转载自xiangjie88.iteye.com/blog/2383622