Ruby/Threads/join

Материал из Wiki.crossplatform.ru

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия: Импорт выборки материалов по Ruby)
 

Текущая версия на 18:00, 13 сентября 2010

Содержание

each thread is given only one second to execute:

threads.each do |thread|
  puts "Thread #{thread.object_id} didn"t finish within 1s" unless thread.join(1)
end



Join a thread after sleeping

meaning_of_life = Thread.new do
  puts "The answer is..."
  sleep 10
  puts 42
end
sleep 9
meaning_of_life.join



Join threads

10.times { Thread.new { 10.times { |i| print i; $stdout.flush; sleep rand(2) } } }
Thread.list.each { |thread| thread.join }



Join two threads

t1 = Thread.new do
  puts "alpha"
  Thread.pass
  puts "beta"
end
t2 = Thread.new do
  puts "gamma"
  puts "delta"
end
t1.join
t2.join



Multithreaded Applications in Ruby

def func1
     i=0
     while i<=3
     puts "func1 at: #{Time.now}"
     sleep(2)
     i=i+1
     end
end
def func2
     j=0
     while j<=3
     puts "func2 at: #{Time.now}"
     sleep(1)
     j=j+1
     end
end
puts "Started At #{Time.now}"
t1=Thread.new{func1()}
t2=Thread.new{func2()}
t1.join
t2.join
puts "End at #{Time.now}"



rescue the exception at the time the threads are joined.

threads = [] 
4.times do |number| 
    threads << Thread.new(number) do |i| 
        raise "Boom!" if i == 2 
        print "#{i}\n" 
    end 
end 
threads.each do |t| 
    begin 
        t.join 
    rescue RuntimeError => e 
        puts "Failed: #{e.message}" 
    end 
end