Last active
December 14, 2015 04:09
-
-
Save keithrbennett/5026007 to your computer and use it in GitHub Desktop.
Ruby script for comparing multithreaded operation in Ruby implementations (eg. Ruby vs. JRuby).
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
| # Simple Ruby/JRuby program to illustrate that MRI Ruby uses only one CPU, | |
| # while JRuby will use all available CPU's. (Inspection tool not included; | |
| # you can use Activity Monitor on a Mac, or htop on many Unix distros. | |
| # | |
| # Keith R. Bennett, @keithrbennett | |
| NUM_THREADS = 5 | |
| SLEEP_DURATION_IN_SEC = 2 | |
| # If running in JRuby, formats a number string with the default locale's | |
| # thousands separator. | |
| def format_integer(number) | |
| if RUBY_PLATFORM == 'java' | |
| # java.util.Locale.default = java.util.Locale::FRANCE | |
| # java.util.Locale.default = java.util.Locale::GERMANY | |
| java.text.NumberFormat.instance.java_send('format', [Java::long], number) | |
| else | |
| number.to_s | |
| end | |
| end | |
| # Function that will be run in each new thread. | |
| def thread_func(thread_num) | |
| iterations = 0 | |
| random_generator = Random.new | |
| loop do | |
| iterations += 1 | |
| if random_generator.rand(10_000_000) == 0 | |
| puts "Hit on thread #{thread_num}, " + | |
| "iteration #{format_integer(iterations)}, " + | |
| "going to sleep for #{SLEEP_DURATION_IN_SEC} seconds(s)." | |
| sleep SLEEP_DURATION_IN_SEC | |
| end | |
| end | |
| end | |
| def main | |
| threads = [] | |
| NUM_THREADS.times do |thread_num| | |
| thread = Thread.new("Thread #{thread_num}") { thread_func(thread_num) } | |
| puts "Started thread_func for thread #{thread_num}, #{thread.inspect}" | |
| threads << thread | |
| end | |
| threads.each { |thread| thread.join } | |
| end | |
| main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment