One of the things that has been nagging me as rails has gone threadsafe is how to do something like store the current user. In non-threadsafe rails, you just store the user id in a class variable or global variable, and you’re done. In threadsafe rails, you end up with obvious concurrency issues from doing that.
The logical place to store the information is in the current thread’s context. That works well for most cases, but what happens if you want to spread work out across threads? And what if those threads need the information in the thread context?
A possible solution is to create a sub-class of Thread that copies parts of the thread context to the new thread’s context. This ended up being pretty easy to do, so I tossed up an example on gist. Here’s the core of it:
class ContextCopyingThread < Thread def initialize self[:x] = Thread.current[:x].dup super end end