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.1.1"

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
# File 'lib/silent_worker.rb', line 9

def initialize(workers = 8, &job)
  @job = job
  @workers = workers
  @threads = []
  @queue = Queue.new
  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



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

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

#abortObject



29
30
31
32
# File 'lib/silent_worker.rb', line 29

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

#startObject



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

def start
  @workers.times do
    @threads << Thread.start(@job, @queue) do |job, queue|
      loop do
        data = queue.pop
        break if @finished && data == FINISH_DATA
        job.call(data)
      end
    end
  end
end

#stopObject



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

def stop
  wait
end

#waitObject



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

def wait
  finish!
  @workers.times do
    @queue.push(FINISH_DATA)
  end
  @threads.each(&:join)
end