Class: Charming::TaskExecutor::Threaded

Inherits:
Object
  • Object
show all
Defined in:
lib/charming/task_executor.rb

Instance Method Summary collapse

Constructor Details

#initialize(queue) ⇒ Threaded

Returns a new instance of Threaded.



6
7
8
9
10
# File 'lib/charming/task_executor.rb', line 6

def initialize(queue)
  @queue = queue
  @threads = []
  @mutex = Mutex.new
end

Instance Method Details

#shutdown(timeout: 0.0) ⇒ Object



19
20
21
22
23
24
25
26
27
28
# File 'lib/charming/task_executor.rb', line 19

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



12
13
14
15
16
17
# File 'lib/charming/task_executor.rb', line 12

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