Ruby/Threads/Ruby Threads
Материал из Wiki.crossplatform.ru
Содержание |
Basic Ruby Threads in Action
threads = [] 10.times do thread = Thread.new do 10.times { |i| print i; $stdout.flush; sleep rand(2) } end threads << thread end threads.each { |thread| thread.join }
Get the value returned from a thread
max = 10000 thr = Thread.new do sum = 0 1.upto(max) { |i| sum += i } sum end puts thr.value
Run this block in a new thread
t = Thread.new do # Run this block in a new thread File.read("data.txt") # Read a file in the background end # File contents available as thread value
Sleep a thread
t1 = Thread.new do puts "Hello" sleep 2 raise "some exception" puts "Goodbye" end t2 = Thread.new { sleep 100 } sleep 2 puts "The End"