Skip to content

Instantly share code, notes, and snippets.

@RyanScottLewis
Created November 18, 2012 17:47
Show Gist options
  • Select an option

  • Save RyanScottLewis/4106497 to your computer and use it in GitHub Desktop.

Select an option

Save RyanScottLewis/4106497 to your computer and use it in GitHub Desktop.
Parallel processing
require 'thread'
require 'bundler/setup'
require 'system'
from, to = Queue.new, Queue.new
item_count = rand(100) + 100
thread_count = (System::CPU.count * 4)
(1..item_count).each { |item| from.push(item) }
puts "Running with #{thread_count} threads on #{item_count} items."
thread_count.times do
Thread.new do
loop do
break if from.empty?
item = from.pop
sleep(rand)
to.push(item)
end
end
end
last_update = Time.now.to_f
items = []
loop do
items << to.pop unless to.empty?
current_item_count = items.length
percent_complete = (current_item_count.to_f / item_count.to_f) * 100.0
percent_complete = '%.2f' % percent_complete
if Time.now.to_f > (last_update + 0.2) # Only update the output 5 times a second.
last_update = Time.now.to_f
print "#{current_item_count}/#{item_count} - #{percent_complete}% complete"
if items.length == item_count
print "\n"
puts 'Done!'
break
else
print " \r"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment