class ThreadExecutor::Processor

A processor is a Queue feeding a Thread.

Public Class Methods

new() click to toggle source

Create Processor.

This will create a new Queue and start a new ruby Thread.

The created thread will block until work is inserted n the Queue using call.

To avoid leaking active threads you must call finish to stop processing and join the Thread behind this object. Once this object is finished it may not be used again. It should be discarded.

Typically the user should never create or use this class, but use an Executor, though there is nothing wrong in using this directly..

# File lib/thread_executor/processor.rb, line 51
def initialize
  @q = Queue.new
  @t = Thread.new do
    while true do
      promise, task = @q.deq

      # This is how we shut down the thread cleanly.
      break if promise.nil? && task.nil?

      begin
        promise.value = task.call
      rescue Exception => e
        promise.exception = e
      end
    end
  end
end

Public Instance Methods

call(&t) click to toggle source

Adds a task, creates a Promise and returns a Future.

# File lib/thread_executor/processor.rb, line 80
def call(&t)
  p = Promise.new
  @q.enq [ p, t ]
  p.future
end
finish() click to toggle source

Call shutdown and join the thread.

This will block until the thread is joined.

When this returns this object is unusable and should be discarded.

# File lib/thread_executor/processor.rb, line 97
def finish
  shutdown
  @t.join
end
shutdown() click to toggle source

Signal that the worker thread should exit.

More precisely, this enqueues a stop request into the work queue, which, when encountered, causes the worker thread to cleanly exit and take no more work.

# File lib/thread_executor/processor.rb, line 75
def shutdown
  @q.enq [nil, nil]
end
size() click to toggle source

Return the size of the work queue.

# File lib/thread_executor/processor.rb, line 87
def size
  @q.size
end