public
Last active

Multi-threading example in ruby.

  • Download Gist
multi_thread_ruby.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
num_iterations = 20
num_threads = 4
 
# Try counting to 1 million on 4 separate threads 20 times
total_time = 0.0
num_iterations.times do |iter|
threads = []
t_0 = Time.now
for i in 1..num_threads
threads << Thread.new(i) { |t|
count = 0
1000000.times do
count += 1
end
}
end
 
# Wait for all threads to complete
threads.each { |thread| thread.join }
t_1 = Time.now
 
time_ms = (t_1-t_0) * 1000
puts "TEST #{iter}: Time elapsed = #{time_ms}ms"
total_time += time_ms
end
 
puts "Average completion time: #{total_time/num_iterations}"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.