Report abuse


			
require 'thread' # Used for Thread::Queue that synchronizes between main thread and job queue
require 'glib2'

class AsyncRunner
  def initialize(sync_client)
    @sync_client = sync_client
    @call_queue = Queue.new
    start
  end

  def start
    @working_thread = Thread.new do
      loop do
        call = @call_queue.deq # Will block until there is a queue to pop
        begin
          ret_val = @sync_client.send(call[0], *call[1])
          GLib::Idle.add { call[2].call(ret_val); false }          
        rescue  => exception
          GLib::Idle.add { raise_exception(exception); break; false}
        end
      end
    end
  end

  def raise_exception
    raise exception.class, "While AsyncRunner called method '#{call[0]}' #{exception}"
  end

  def stop
    unless @working_thread.nil?
      @working_thread.exit
    end
  end

  def method_missing(method_id, *arguments, &block)
    call = [method_id, arguments, block]
    @call_queue.enq(call)
  end

  def respond_to?(n)
    @sync_client.respond_to?(n)
  end
end