Skip to content

Instantly share code, notes, and snippets.

@dwaite
Created February 2, 2012 23:07
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 dwaite/1726352 to your computer and use it in GitHub Desktop.
Save dwaite/1726352 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
# Set two thread locals
Thread.current["foo"] = "fooval"
Thread.current["bar"] = "barval"
puts [Thread.current["foo"], Thread.current["bar"]]
# prints:
# fooval
# barval
# Create a new fiber which sets one thread local then prints out the two above
f = Fiber.new do Thread.current["foo"] = "newval"
Thread.current["foo"] = "newfoo"
puts [Thread.current["foo"], Thread.current["bar"]]
end
f.resume
# prints:
# fooval
# <blank>
# Thread.current only contains locals for a Fiber, and does not fall back on locals for a thread. This interferes with systems that may create an object per thread as an efficiency against locking. AFAICT, there is no way to get the real locals for a thread from within a fiber.
puts f.methods - Object.instance_methods
# prints:
# [:resume]
# The values of Thread.current within a fiber (fiber locals) are not accessible, nor modifiable from
# the outside. Some environments may set context data as a thread local, under the assumption
# that only one activity (with a single context) can be processed on a thread at the same time. The
# inaccessibility of fiber locals from outside a fiber greatly complicate having activity setup outside
# a fiber while processing happens within a fiber.
@avdi
Copy link

avdi commented Feb 2, 2012

Good to know! Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment