I'm wondering if there are some serious implications I might be creating for myself by using thread locals. I noticed that in the case of Flask, they use thread locals, and mention that it can cause issues with servers that aren't built with threads in mind. Is this an outdated concern? I'm using thread locals with Django for a few things, deploying with NGINX in front of UWSGI, or Gunicorn, on Ubuntu 10.04 with Postgres (not that the OS or DB probably matter, but just for clarity). Do I need to be worried?
Asked
Active
Viewed 1,556 times
3
-
If you're worried about performance, just benchmark it yourself. I don't expect any problems. – Glenn Maynard Nov 05 '10 at 09:40
1 Answers
0
Threadlocals aren't the most robust or secure way to do things - check out this note, for instance. [ Though also see Glenn's comment, below ]
I suppose if you have coded cleanly, with the idea that you're putting stuff into a big global pot of info, accepting unguaranteed data consistency in those threaded locals and taking care to avoid race conditions, etc, etc, you might well be ok.
But, even with that in mind, there's still the 'magic'ness of threaded local vars, so documenting clearly what the heck is going on and any time a threadedlocal var is used might help you/future developers of the codebase down the line.

Steve Jalim
- 11,989
- 1
- 37
- 54
-
4That note is simply bad advice. Thread-local variables are an excellent solution for things like storing the current user's info. Just be sure to clear the all thread-local vars in your exception middleware. Globals are no more *inherently* bad than C's `goto`; they just need to be used with care. – Glenn Maynard Nov 05 '10 at 09:35
-
+1 Glenn. I guess that was the main thrust of what I was saying: do it carefully, and document it clearly, then you reduce the risk of sanity-sapping bugs – Steve Jalim Nov 05 '10 at 10:12
-
thanks. I avoid race conditions by using a function to get values only in the context where the thread locals middleware have already run. – orokusaki Nov 05 '10 at 18:26
-
1I've used threadlocals in the past but not a big fan now. If you must use them check out fluid bindings: http://thisismedium.com/tech/fluid-bindings-python/ – Van Gale Nov 05 '10 at 22:01
-
2stevejalim this link not loger exists: The page CookBookThreadlocalsAndUser does not exist. You can create it here. – panchicore May 03 '12 at 01:11