Class: SilentWorker

Inherits:
Object
  • Object
show all
Defined in:
lib/silent_worker.rb,
lib/silent_worker/version.rb

Constant Summary collapse

FINISH_DATA =

EOT

"\x04"
VERSION =
"0.2.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(workers = 8, &job) ⇒ SilentWorker

Returns a new instance of SilentWorker.


9
10
11
12
13
14
15
16
# File 'lib/silent_worker.rb', line 9

def initialize(workers = 8, &job)
  @job = job
  @workers = workers
  @threads = []
  @queue = Queue.new
  setup_signal_traps
  start
end

Instance Attribute Details

#jobObject (readonly)

Returns the value of attribute job


5
6
7
# File 'lib/silent_worker.rb', line 5

def job
  @job
end

#queueObject (readonly)

Returns the value of attribute queue


5
6
7
# File 'lib/silent_worker.rb', line 5

def queue
  @queue
end

#workersObject (readonly)

Returns the value of attribute workers


5
6
7
# File 'lib/silent_worker.rb', line 5

def workers
  @workers
end

Instance Method Details

#<<(data) ⇒ Object


18
19
20
# File 'lib/silent_worker.rb', line 18

def <<(data)
  @queue.enq(data)
end

#abortObject Also known as: stop!


27
28
29
30
# File 'lib/silent_worker.rb', line 27

def abort
  @threads.each(&:kill)
  wait
end

#startObject


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/silent_worker.rb', line 37

def start
  return if @working

  @working = true
  @finished = false
  @workers.times do |n|
    @threads << Thread.start(@job, @queue, n) do |job, queue, n|
      Thread.current[:num] = n
      loop do
        data = queue.deq
        break if @finished && data == FINISH_DATA
        job.call(data)
      end
    end
  end
end

#stopObject


33
34
35
# File 'lib/silent_worker.rb', line 33

def stop
  finish!
end

#waitObject


22
23
24
25
# File 'lib/silent_worker.rb', line 22

def wait
  finish!
  @threads.find_all(&:alive?).each(&:join)
end