views:

478

answers:

2

In python with all this idea of "Everything is an object" where is thread-safety?

I am developing django website with wsgi. Also it would work in linux, and as I know they use effective process management, so we could not think about thread-safety alot. I am not doubt in how module loads, and there functions are static or not? Every information would be helpfull.

+5  A: 

Functions in a module are equivalent to static methods in a class. The issue of thread safety arises when multiple threads may be modifying shared data, or even one thread may be modifying such data while others are reading it; it's best avoided by making data be owned by ONE module (accessed via Queue.Queue from others), but when that's not feasible you have to resort to locking and other, more complex, synchronization primitives.

This applies whether the access to shared data happens in module functions, static methods, or instance methods -- and the shared data is such whether it's instance variables, class ones, or global ones (scoping and thread safety are essentially disjoint, except that function-local data is, to a pont, intrinsically thread-safe -- no other thread will ever see the data inside a function instance, until and unless the function deliberately "shares" it through shared containers).

If you use the multiprocessing module in Python's standard library, instead of the threading module, you may in fact not have to care about "thread safety" -- essentially because NO data is shared among processes... well, unless you go out of your way to change that, e.g. via mmapped files;-).

Alex Martelli
A: 

See the python documentation to better understand the general thread safety implications of Python.

Django itself seems to be thread safe as of 1.0.3, but your code may not and you will have to verify that...

My advice would be to simply don't care about that and serve your application with multiple processes instead of multiple threads (for example by using apache 'prefork' instead of 'worker' MPM).

Luper Rouch
You don't have to use prefork MPM. You could use mod_wsgi daemon mode. In that case you can still use worker MPM as number of processes and threads used by mod_wsgi daemon mode is separately controlled. Use of prefork would only be required for mod_python or embedded mode of mod_wsgi.
Graham Dumpleton