Class: EMRPC::MultithreadedClient

Inherits:
Object
  • Object
show all
Defined in:
lib/emrpc/multithreaded_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ MultithreadedClient

Returns a new instance of MultithreadedClient.



6
7
8
9
10
11
12
13
14
# File 'lib/emrpc/multithreaded_client.rb', line 6

def initialize(options)
  @backends = options[:backends] or raise "No backends supplied!"
  @pool     = options[:queue] || ::Queue.new
  @timeout  = options[:timeout] || 5
  @timeout_thread = Thread.new { timer_action! }
  @backends.each do |backend|
    @pool.push(backend)
  end
end

Instance Attribute Details

#backendsObject (readonly)

Returns the value of attribute backends.



5
6
7
# File 'lib/emrpc/multithreaded_client.rb', line 5

def backends
  @backends
end

#poolObject (readonly)

Returns the value of attribute pool.



5
6
7
# File 'lib/emrpc/multithreaded_client.rb', line 5

def pool
  @pool
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



5
6
7
# File 'lib/emrpc/multithreaded_client.rb', line 5

def timeout
  @timeout
end

Instance Method Details

#send_message(meth, args, blk) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/emrpc/multithreaded_client.rb', line 16

def send_message(meth, args, blk)
  start = Time.now
  # wait for the available connections here
  while :timeout == (backend = @pool.pop)
    seconds = Time.now - start
    if seconds > @timeout
      raise PoolTimeout, "Thread #{Thread.current} waited #{seconds} seconds for backend connection in a pool. Pool size is #{@backends.size}. Maybe too many threads are running concurrently. Increase the pool size or decrease the number of threads."
    end
  end
  begin
    backend.send_message(meth, args, blk)
  ensure # Always push backend to a pool after using it!
    @pool.push(backend)
  end
end

#timer_action!Object

Pushes :timeout message to a queue for all the threads in a backlog every @timeout seconds.



34
35
36
37
# File 'lib/emrpc/multithreaded_client.rb', line 34

def timer_action!
  sleep @timeout
  @pool.num_waiting.times { @pool.push(:timeout) }
end