Class: Performer
- Inherits:
-
Object
- Object
- Performer
- Defined in:
- lib/performer.rb,
lib/performer/task.rb,
lib/performer/queue.rb,
lib/performer/version.rb,
lib/performer/condition_variable.rb
Overview
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.
Defined Under Namespace
Classes: ConditionVariable, Error, Queue, ShutdownError, Task
Constant Summary collapse
- VERSION =
Current version of Performer.
"1.0.1"
Instance Attribute Summary collapse
-
#thread ⇒ Thread
readonly
If you ever need to forcefully kill the Performer (don’t do that), here’s the thread you’ll need to attack.
Instance Method Summary collapse
-
#async { ... } ⇒ Performer::Task
Asynchronously schedule a block for execution.
-
#initialize ⇒ Performer
constructor
A new instance of Performer.
-
#shutdown ⇒ Performer::Task
Asynchronously schedule a shutdown, allowing all previously queued tasks to finish.
-
#sync(timeout = nil) { ... } ⇒ Object
Synchronously schedule a block for execution.
Constructor Details
#initialize ⇒ Performer
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
#thread ⇒ Thread (readonly)
If you ever need to forcefully kill the Performer (don’t do that), here’s the thread you’ll need to attack.
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.
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 |
#shutdown ⇒ Performer::Task
No additional tasks will be accepted after shutdown.
Asynchronously schedule a shutdown, allowing all previously queued tasks to finish.
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.
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 |