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?
Thread#[]
andThread#[]=
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.