Fiber Local vs Thread Local Variable
fibers, multithreading, ruby, ruby-on-rails
Solution
The answer would depend on whether your web-server utilizes threads or fibers to serve multiple users concurrently.
A surprising number of ruby web-servers utilizes neither - they either serve only one client at a time (like Webrick and Thin), or uses processes to serve multiple users (like passenger over nginx).
However, it seems that there is an answer which will work in each of these cases (multi-thread, multi-fiber, or multi-process), thanks to small implementation favors, as shown in this blog post:
Ruby Thread Locals are also Fiber-Local
I was briefly concerned that thread-local variables would not also be Fiber-local, since fibers have their own stack. This would be a problem for any code which uses thread-local variables to delimit a stack context, e.g. to implement dynamically-scoped variables or to prevent recursion. My fears, however, were easily allayed.
Once again, Ruby gets the little things right.
Bottom line - use thread-local - it should work.
Problem
I am very confused on when to use fiber local variables over thread local variables in rails. My use case is following: I have a controller in rails which on a GET request does some computation and stores the result (which is a list of integers) in either fiber or thread local variable. I need to do this so that I can excess this computed result in lets say a model which might be created by controller. Now I don't want to store it in session since this computation must be done for each and every GET request. I also clear up the fiber/thread local variable just before GET method in controller completes. Now I do see that both Fibre and Thread are quite different and hence their storage variables. Can anyone please explain when to use which kind of variable ? Actually my understanding is as follows: it seems that two requests can never be served in same fiber/thread at the same time. Hence if I have a value that I want to put in request scope, either one should be fine. Is my explanation correct ?