Sha256: 55b46592987bb438767916fbc38dc8a19f6e87b8fd0306c11b6dac90584599b8

Contents?: true

Size: 1.36 KB

Versions: 1

Compression:

Stored size: 1.36 KB

Contents

require 'tools/waiting_queue.rb'

class MessageQueue
  MIDDLE_PRIORITY=10
  
  def initialize(node,priority=nil)
    
    priority||=MIDDLE_PRIORITY
    
    @priority=priority
    
    @node=node

    @receivers={}
    
    @mutex=Mutex.new
    @recMutex=Mutex.new
    @pkgId=0
    
    @node.addReceiver(self) {|from,args|
      receive(from,args)
    }
    
    @inQueue=WaitingQueue.new
    @outQueue=WaitingQueue.new
    
    @rThread=Thread.new { receiveThread}
    @sThread=Thread.new { sendThread}
  end
  
  def me
    @node.me
  end
  
  def addReceiver(api,&block)
    @receivers[api]=block
  end
  
  def removeReceiver(app)
    @receivers.delete(app)
  end
  def log(*x)
    @node.log(*x)
  end

  # close the api-object - api won't listen anymore
  def close
    @rThread.stop
    @node.removeReceiver(self)
  end

  def receive(from,args)
    @inQueue<<[from,args]
  end
  
  def sendMessage(data,node)
    @outQueue<<[data,node]
  end
  
  private
  def receiveThread
    begin
      loop do
        e=@inQueue.pop
        from,data=e
        @receivers.each{|k,v|v.call(from,data)}
        pp e
      end
    rescue Object=>e
      pp e,e.backtrace
    end
  end
  def sendThread
    begin
      loop do
        e=@outQueue.pop
        data,node=e
        @node.sendMessage(data,node)
        #sleep 0.2
      end
    rescue Object=>e
      pp e,e.backtrace
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
appswarm-0.0.1 apps/udp_network/message_queue.rb