Class: Performer

Inherits:
Object
  • Object
show all
Defined in:
lib/performer.rb,
lib/performer/task.rb,
lib/performer/queue.rb,
lib/performer/version.rb,
lib/performer/condition_variable.rb

Overview

Note:

The Performer is thread-safe.

Performer is the main entry point and namespace of the Performer gem. It provides methods for synchronously and asynchronously scheduling blocks for execution in the performer thread, and a way to shut down the performer cleanly.

Examples:

usage

performer = Performer.new
performer.sync { 1 + 1 } # => 2
performer.async { 1 + 1 } # => Performer::Task

Defined Under Namespace

Classes: ConditionVariable, Error, Queue, ShutdownError, Task

Constant Summary collapse

VERSION =

Current version of Performer.

"1.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePerformer

Returns a new instance of Performer.



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/performer.rb', line 21

def initialize
  @queue = Performer::Queue.new
  @running = true
  @thread = Thread.new(&method(:run_loop))

  @current_task = nil
  @shutdown_task = Task.new(lambda do
    @running = false
    nil
  end)
end

Instance Attribute Details

#threadThread (readonly)

If you ever need to forcefully kill the Performer (don’t do that), here’s the thread you’ll need to attack.

Returns:

  • (Thread)


37
38
39
# File 'lib/performer.rb', line 37

def thread
  @thread
end

Instance Method Details

#async { ... } ⇒ Performer::Task

Asynchronously schedule a block for execution.

Yields:

  • block to be executed

Returns:

Raises:



62
63
64
65
# File 'lib/performer.rb', line 62

def async(&block)
  task = Task.new(block)
  @queue.enq(task) { raise ShutdownError, "performer is shut down" }
end

#shutdownPerformer::Task

Note:

No additional tasks will be accepted after shutdown.

Asynchronously schedule a shutdown, allowing all previously queued tasks to finish.

Returns:

Raises:



73
74
75
76
77
78
79
# File 'lib/performer.rb', line 73

def shutdown
  @queue.close(@shutdown_task) do
    raise ShutdownError, "performer is shut down"
  end

  @shutdown_task
end

#sync(timeout = nil) { ... } ⇒ Object

Synchronously schedule a block for execution.

If run from inside a task in the same performer, the block is executed immediately. You can avoid this behavior by using #async instead.

Parameters:

  • timeout (Integer, nil) (defaults to: nil)

    (see Task#value)

Yields:

  • block to be executed

Returns:

  • whatever the block returned

Raises:

  • (TimeoutError)

    if waiting for the task to finish timed out

  • (ShutdownError)

    if shutdown has been requested



49
50
51
52
53
54
55
# File 'lib/performer.rb', line 49

def sync(timeout = nil, &block)
  if Thread.current == @thread
    yield
  else
    async(&block).value(timeout)
  end
end