Last active
May 3, 2017 21:03
-
-
Save abachman/08f79c95aa50c0952b4fab5cf881ec06 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# worker | |
require 'thread' | |
queue = Queue.new | |
threads = [] | |
puts 'create workers' | |
10.times do |n| | |
threads << Thread.new(n) do |c| | |
# each worker waits before starting | |
sleep 1 | |
loop do | |
a = queue.pop | |
if a.nil? | |
puts "#{c} quitting" | |
break | |
else | |
puts "#{c} #{a}" | |
# simulate work | |
sleep(rand() * 0.2) | |
end | |
end | |
end | |
end | |
puts 'add work' | |
start = Time.now | |
190.times do |n| | |
queue.push(start + n) | |
end | |
puts 'add work stop signal (nil value)' | |
threads.size.times { queue.push(nil) } | |
puts 'wait for each thread to complete' | |
threads.each { |t| t.join } | |
puts "DONE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment