Skip to content

Instantly share code, notes, and snippets.

@takuma-saito
Created May 2, 2020 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takuma-saito/34b28beacbbcca0f6fcb6f3a07f7d271 to your computer and use it in GitHub Desktop.
Save takuma-saito/34b28beacbbcca0f6fcb6f3a07f7d271 to your computer and use it in GitHub Desktop.
worker.rb
require 'thread'
class Workers
def initialize(count)
@q = Queue.new
@count = count
@jobs = (0...@count).map.with_index {|id|
Thread.new do
while (job = @q.pop)
total = job.(id, total)
end
end
}
end
def push(&proc)
@q.push(proc)
end
def wait
@count.times { @q.push(nil) }
@jobs.each {|job| job.join.value}
ensure
@q.close
end
end
w = Workers.new(60)
(0..120).each do |i|
w.push do |id, total|
sleep (r = (rand * 5))
total = r + (total || 0)
puts "[%02d]: %02d %2.2f %2.2f" % [id, i, r, total]
total
end
end
w.wait
p 'done'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment