Skip to content

Instantly share code, notes, and snippets.

@igaiga
Created April 24, 2020 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igaiga/94b4ad35176184058cec26a71a822810 to your computer and use it in GitHub Desktop.
Save igaiga/94b4ad35176184058cec26a71a822810 to your computer and use it in GitHub Desktop.
### Thread.current is fiber local
f = Fiber.new do
Thread.current[:foo] = 0
loop do
Fiber.yield(Thread.current[:foo])
Thread.current[:foo] += 1
end
end
f2 = Fiber.new do
Thread.current[:foo] = 100
loop do
Fiber.yield(Thread.current[:foo])
Thread.current[:foo] += 2
end
end
5.times do
p f.resume
p f2.resume
end
# $ ruby thread_current.rb
# 0
# 100
# 1
# 102
# 2
# 104
# 3
# 106
# 4
# 108
### Global val case
f = Fiber.new do
$foo = 0
loop do
Fiber.yield($foo)
$foo += 1
end
end
f2 = Fiber.new do
$foo = 100
loop do
Fiber.yield($foo)
$foo += 2
end
end
5.times do
p f.resume
p f2.resume
end
# $ ruby global.rb
# 0
# 100
# 101
# 103
# 104
# 106
# 107
# 109
# 110
# 112
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment