Class: SilentWorker
- Inherits:
-
Object
- Object
- SilentWorker
- 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
-
#job ⇒ Object
readonly
Returns the value of attribute job.
-
#queue ⇒ Object
readonly
Returns the value of attribute queue.
-
#workers ⇒ Object
readonly
Returns the value of attribute workers.
Instance Method Summary collapse
- #<<(data) ⇒ Object
- #abort ⇒ Object (also: #stop!)
-
#initialize(workers = 8, &job) ⇒ SilentWorker
constructor
A new instance of SilentWorker.
- #start ⇒ Object
- #stop ⇒ Object
- #wait ⇒ Object
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
#job ⇒ Object (readonly)
Returns the value of attribute job.
5 6 7 |
# File 'lib/silent_worker.rb', line 5 def job @job end |
#queue ⇒ Object (readonly)
Returns the value of attribute queue.
5 6 7 |
# File 'lib/silent_worker.rb', line 5 def queue @queue end |
#workers ⇒ Object (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 |
#abort ⇒ Object Also known as: stop!
27 28 29 30 |
# File 'lib/silent_worker.rb', line 27 def abort @threads.each(&:kill) wait end |
#start ⇒ Object
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 |
#stop ⇒ Object
33 34 35 |
# File 'lib/silent_worker.rb', line 33 def stop finish! end |
#wait ⇒ Object
22 23 24 25 |
# File 'lib/silent_worker.rb', line 22 def wait finish! @threads.find_all(&:alive?).each(&:join) end |