2

This code:

Fiber.new do 
  Thread.current['a'] = 5

  p Thread.current.object_id
  p Thread.current['a']

  Fiber.new do 
    p Thread.current.object_id
    p Thread.current['a']
  end.resume

  p Thread.current.object_id
  p Thread.current['a']
end.resume

shows the following results:

3442840
5

3442840
nil

3442840
5

Why does current['a'] return nil in nested fiber? How can it be explained?

sawa
  • 165,429
  • 45
  • 277
  • 381
the-teacher
  • 589
  • 8
  • 19

1 Answers1

1

Thread#[] and Thread#[]= are not thread-local but fiber-local. This confusion did not exist in Ruby 1.8 because fibers were only available since Ruby 1.9. Ruby 1.9 chooses that the methods behaves fiber-local to save following idiom for dynamic scope.

— Thread class doc

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160