気軽に楽しくプログラムと遊ぶ

自分が興味があってためになるかもって思う情報を提供しています。

Ruby Threadクラスの基本

スレッドの作成、終了、停止、例外発生時のスレッドの挙動について確認していきます。

プログラム開始時に生成されるスレッドをメインスレッドと呼ぶ。メインスレッドで 動かすスレッドについて以下より見ていきます。

スレッドの作成

Thread::new、Thread::start、Thread::forkにより新しいスレッドを生成することができます。

puts "create thread"

# スレッド作成
t = Thread.new do
  puts "start thread"
  # 3秒停止する
  sleep 3
  puts "end thread"
end

puts "wating for the thread to complete"
# スレッド処理が終了するのを待つ
t.join

# スレッド終了後に下記が実行される
puts "completed"

実行結果

create thread
start thread
waiting for the thread to complete
end thread
compleated

スレッドの終了

Thread#killメソッドによりメインスレッドからスレッドの実行を終了させることが可能

puts "create thread"

t = Thread.new do
  puts "start thread"
  sleep 10
  puts "end thread"
end

# スレッドを終了させる
Thread.kill(t)
puts "the thread killed"

実行結果

create thread
start thread
the thread killed
# end threadは表示されない。

スレッドを停止させる

Thread#stopによりカレントスレッドを停止できる。
停止スレッドは他のスレッドにThread#runメソッドにより起動されるまで停止しています。

puts "create thread"

t = Thread.new do
  puts "start thread"
  Thread.stop
  puts "end thread"
end

# 標準入力より入力待ちになる
gets
# スレッドが再開する
t.run
t.join

puts "completed"

実行結果

create thread
start thread
end thread
completed

例外発生時のスレッドの挙動

スレッド内で例外が発生し、resucueで捕捉されない場合、そのスレッドが警告なしに終了する。

例外発生時にそのスレッドをThread#joinで待っているスレッドが存在する場合、
その待っているスレッドに対して、同じ例外を発生させます。

begin
  t = Thread.new do
    raise
  end
  # joinがないと警告なしでスレッドが終了
  t.join
rescue
  p "例外が発生しました"
end

#=> "例外が発生しました"

いずれかのスレッドが例外によって終了した場合、インタプリタ全体を中断させる方法

参考URL

http://www.namaraii.com/rubytips/?%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89