Skip to content

Instantly share code, notes, and snippets.

@abachman
Last active May 3, 2017 21:03
Show Gist options
  • Save abachman/08f79c95aa50c0952b4fab5cf881ec06 to your computer and use it in GitHub Desktop.
Save abachman/08f79c95aa50c0952b4fab5cf881ec06 to your computer and use it in GitHub Desktop.
# 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