Class: Charming::Tasks::ThreadedExecutor
- Inherits:
-
Object
- Object
- Charming::Tasks::ThreadedExecutor
- Defined in:
- lib/charming/tasks/threaded_executor.rb
Overview
ThreadedExecutor runs submitted tasks on background Ruby threads. Each submission creates a new thread that invokes the block and pushes the resulting TaskEvent onto the shared queue. Threads are tracked so ‘shutdown` can wait (or kill) in-flight work.
Instance Method Summary collapse
-
#initialize(queue) ⇒ ThreadedExecutor
constructor
queue is the thread-safe Queue (typically ‘runtime.@task_queue`) into which completed TaskEvents are pushed.
-
#shutdown(timeout: 0.0) ⇒ Object
Waits up to timeout seconds for in-flight threads to finish, then kills any remaining live threads.
-
#submit(name, &block) ⇒ Object
Wraps block in a Task and spawns a new thread to invoke it.
Constructor Details
#initialize(queue) ⇒ ThreadedExecutor
queue is the thread-safe Queue (typically ‘runtime.@task_queue`) into which completed TaskEvents are pushed.
12 13 14 15 16 |
# File 'lib/charming/tasks/threaded_executor.rb', line 12 def initialize(queue) @queue = queue @threads = [] @mutex = Mutex.new end |
Instance Method Details
#shutdown(timeout: 0.0) ⇒ Object
Waits up to timeout seconds for in-flight threads to finish, then kills any remaining live threads. Used by Runtime during teardown.
30 31 32 33 34 35 36 37 38 39 |
# File 'lib/charming/tasks/threaded_executor.rb', line 30 def shutdown(timeout: 0.0) threads = @mutex.synchronize { @threads.dup } threads.each { |thread| thread.join(timeout) } threads.each do |thread| next unless thread.alive? thread.kill thread.join(0) end end |
#submit(name, &block) ⇒ Object
Wraps block in a Task and spawns a new thread to invoke it. The thread’s return value (or rescued exception) is pushed onto the queue as a TaskEvent. Returns nil immediately.
21 22 23 24 25 26 |
# File 'lib/charming/tasks/threaded_executor.rb', line 21 def submit(name, &block) task = Task.new(name: name.to_sym, block: block) thread = Thread.new(task) { |t| @queue << run(t) } @mutex.synchronize { @threads << thread } nil end |