Skip to content

Instantly share code, notes, and snippets.

@carlesjove
Last active December 20, 2020 09:28
Show Gist options
  • Save carlesjove/4d1f2ac6e8b012e98967d1d6b74226d8 to your computer and use it in GitHub Desktop.
Save carlesjove/4d1f2ac6e8b012e98967d1d6b74226d8 to your computer and use it in GitHub Desktop.
Ruby program in multiple threads (proof of concept)
# List of IDs of entities to be processed
ids = ("a".."z").to_a
# Break in groups of 5 (or any other number)
groups = ids.each_slice(5)
# Make sure that exceptions will spread.
# By default the are silenced within threads
# so you want know why your program crashed.
Thread.abort_on_exception = true
threads = []
groups.each_with_index do |group, index|
ids_to_process = group.join(",")
threads << Thread.new do
system "ruby main.rb #{ids_to_process} > log-group-#{index}.txt"
puts "Started process for group #{index}"
puts "Inspect logs by running tail -f log-group-#{index}.txt"
end
end
threads.each(&:join)
ids_to_process = ARGV[0].split(",")
ids_to_process.each do |id|
puts "************************"
puts "Processing #{id}"
# Just to make it randomly slow and have time to see the logs
(1_000_000..10_000_000).to_a.sample.times { print "." }
puts "******** END ***********"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment