开发者

Pythonic thread-safe object

开发者 https://www.devze.com 2023-04-03 04:32 出处:网络
After reading a lot on this subject and discussing on IRC, the response seems to be: stay away from threads. Sorry for repeating this question, my intention is to go deeper in the subject by not accep

After reading a lot on this subject and discussing on IRC, the response seems to be: stay away from threads. Sorry for repeating this question, my intention is to go deeper in the subject by not accepting the "threading is evil" answer, with 开发者_StackOverflow中文版the hope to find a common solution.

EDIT: Just Say No to the combined evils of locking, deadlocks, lock granularity, livelocks, nondeterminism and race conditions. --Guido van Rossum

I'm developing a Python web application, and I'd like to create a global object for each user which is only accessible by the current user. (for example the requested URI)

The suggested way is to pass the object around, which IMO makes the application harder to maintain, and not beautiful code if I need the same value in different places (some might be 3rd party plugins).

I see that many popular frameworks (Django, CherryPy, Flask) use Python threading locks to solve the issue. If all these frameworks go against the Pythonic way and feel the need to create a globally accessible object, it means that the community needs this sort of thing. And me too.

Is the "best" way to pass objects around? Is the only alternative solution to use the "evil" threading locks? Would it be more Pythonic to store this information in a database or memcached?

Thanks in advance!


If you don't want to lock, then either don't use globals, or use thread-local storage (in a webapp, you can be fairly sure that a request won't cross thread boundary). If global state can be avoided, it should be avoided. This makes multi-threading way easier to implement and debug.

I also disagree that passing objects around makes the application harder to maintain — it's usually the other way around — global state hides dependencies in addition to requiring careful synchronisation.

Well, there also lock-free approaches, like STM or whatnot, but it's probably an overkill for a web application.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号