Tuesday, May 19, 2009

Ruby Threads Example

#!/usr/bin/ruby
f1 = STDOUT
t1 = Thread.new {
f1.puts "Thread 1 started"
25.times {|n|
f1.puts "Thread 1 is writing #{n}"
sleeptime = rand(100).to_f/100
sleep sleeptime
}
}
t2 = Thread.new {
f1.puts "Thread 2 started"
25.times {|n|
f1.puts "Thread 2 is writing #{n}"
sleeptime = rand(100).to_f/100
sleep sleeptime
}
}

f1.puts "Joining threads, if you had not joined, the main program would have quit here, thereby killing the threads before completion"
t1.join
t2.join