Class: Ji2p::Startup::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/ji2p/startup/worker.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(num_threads:, queue:) ⇒ Worker

Returns a new instance of Worker.



11
12
13
14
15
# File 'lib/ji2p/startup/worker.rb', line 11

def initialize(num_threads:, queue:)
  @num_threads = num_threads
  @queue = queue
  @threads = []
end

Instance Attribute Details

#num_threadsObject (readonly)

Returns the value of attribute num_threads.



17
18
19
# File 'lib/ji2p/startup/worker.rb', line 17

def num_threads
  @num_threads
end

Class Method Details

.start(num_threads:, queue_size:) ⇒ Object



4
5
6
7
8
9
# File 'lib/ji2p/startup/worker.rb', line 4

def self.start(num_threads:, queue_size:)
  queue = SizedQueue.new(queue_size)
  worker = new(num_threads: num_threads, queue: queue)
  worker.spawn_threads
  worker
end

Instance Method Details

#enqueue(action, payload) ⇒ Object



31
32
33
# File 'lib/ji2p/startup/worker.rb', line 31

def enqueue(action, payload)
  queue.push([action, payload])
end

#spawn_threadsObject



20
21
22
23
24
25
26
27
28
29
# File 'lib/ji2p/startup/worker.rb', line 20

def spawn_threads
  num_threads.times do
    threads << Thread.new do
      while running? || actions?
        action_proc, action_payload = wait_for_action
        action_proc.call(action_payload) if action_proc
      end
    end
  end
end

#stopObject



35
36
37
38
39
40
# File 'lib/ji2p/startup/worker.rb', line 35

def stop
  queue.close
  threads.each(&:exit)
  threads.clear
  true
end