Created
April 24, 2020 09:30
-
-
Save igaiga/94b4ad35176184058cec26a71a822810 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 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