Module: EventMachine

Defined in:
lib/em-simple_telnet.rb

Overview

This defines EventMachine::defers_finished? which is used by StopWhenEMDone to stop EventMachine safely when everything is done. The method returns true if the @threadqueue and @resultqueue are undefined/nil/empty and none of the threads in the threadpool isn't working anymore.

To do this, the method ::spawn_threadpool is redefined to start threads that provide a thread-local variable :working (like thread_obj[:working]). This variable tells whether the thread is still working on a deferred action or not.

Class Method Summary (collapse)

Class Method Details

+ (Boolean) defers_finished?

Returns:

  • (Boolean)


18
19
20
21
22
# File 'lib/em-simple_telnet.rb', line 18

def self.defers_finished?
  (not defined? @threadqueue or (tq=@threadqueue).nil? or tq.empty? ) and
  (not defined? @resultqueue or (rq=@resultqueue).nil? or rq.empty? ) and
  (not defined? @threadpool  or (tp=@threadpool).nil? or tp.none? {|t|t[:working]})
end

+ (Object) spawn_threadpool



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/em-simple_telnet.rb', line 24

def self.spawn_threadpool
  until @threadpool.size == @threadpool_size.to_i
    thread = Thread.new do
      Thread.current.abort_on_exception = true
      while true
        Thread.current[:working] = false
        op, cback = *@threadqueue.pop
        Thread.current[:working] = true
        result = op.call
        @resultqueue << [result, cback]
        EventMachine.signal_loopbreak
      end
    end
    @threadpool << thread
  end
end