LoginSignup
0
0

More than 1 year has passed since last update.

RubyのFiberクラス

Posted at

定義

 Fiber クラスは、他の言語で coroutine や semicoroutine と呼ばれる軽量スレッドであるファイバーを提供するクラスです。明示的に指定しない限りコンテキスが切り替わらないことや親子関係を持つなど、Thread クラスを提供するスレッドとは異なる挙動と持ちます。
 Fiber.new メソッドにブロックを渡すと、Fiber クラスのオブジェクトであるファイバーが生成されます。このファイバーはインスタンスメソッドである resume メソッドでコンテキストがファイバーに切り替わります。また Fiber.yield メソッドで親である呼び出し元へコンテキストが切り替わります。

事例

fiber_sample.rb
f = Fiber.new {
  print "A "
  Fiber.yield "B "
  print "C "
}

print "D "
print f.resume
print "E "

結果

[3] pry(main)> f = Fiber.new {
  print "A "
  Fiber.yield "B "
  print "C "
}
print "D "
print f.resume
print "E "

D A B E => nil

解析

 Fiber のブロック内は f.resume が呼び出された時に評価され、 Fiber.yield まで実行します。 Fiber.yield が呼ばれると、引数の"B"と共に元のコンテキストに処理を戻します。もし再び f.resumeが呼ばれると Fiber.yield の次の行から実行します。

[4] pry(main)> print f.resume
C => nil
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0