Last active
December 21, 2015 03:48
-
-
Save FilBot3/2799f2c2fe36149470ea to your computer and use it in GitHub Desktop.
Ruby Threading Example
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
| #!/usr/bin/env ruby | |
| # | |
| # | |
| # | |
| @threads = [] | |
| 6.times do |i| | |
| @threads[i] = Thread.new do | |
| sum = 1 + rand(100) | |
| while true do | |
| sleep 0.5 | |
| sum += 1 | |
| Thread.current["thread_sum"] = sum | |
| if sum == 100 | |
| sum = 0 | |
| end | |
| end | |
| end | |
| end | |
| def run! | |
| while true do | |
| sleep 1 | |
| thread_num = rand(6) | |
| puts "Thread #{thread_num} = " + "#{@threads[thread_num]['thread_sum']}" | |
| end | |
| rescue SignalException => e | |
| puts "SignalException: #{e}" | |
| puts "Ending the program." | |
| exit 0 | |
| rescue Interrupt => e | |
| puts "Interrupt: #{e}" | |
| puts "Exiting the program." | |
| exit 0 | |
| rescue Exception => e | |
| puts "Exception: #{e}" | |
| puts "Exiting the program." | |
| exit 0 | |
| end | |
| # Run the run! method | |
| run! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment