Are Python global variables thread-safe?
edit: im asking if global variables are safe in a single-threaded web framework like tornado
im using the mongoengine orm, which gets a database connection from a global variable:
_get_db() # gets the db connection
im also using tornado, a single-threaded python web framework. in one particular view, i need to grab a database connection and dereference a DBRef
object [similar to a foreign key]:
# dereference a DBRef
_get_db().dereference(some_db_ref)
since the connection returned by _get_db
is a global var, is there a possibility of colli开发者_如何转开发sion and the wrong value being returned to the wrong thread?
Threads are always required to hold the GIL when interacting with Python objects. The namespace holding the variables is a Python object (either a frameobject or a dict, depending on what kind of variable it is.) It's always safe to get or set variables in multiple threads. You will never get garbage data.
However, the usual race conditions do apply as to which object you get, or which object you replace when you assign. A statement like x += 1
is not thread-safe, because a different thread can run between the get and the store, changing the value of x
, which you would then overwrite.
Assuming MongoEngine is wrapping PyMongo (and I believe it is), then you should be fine. PyMongo is completely thread-safe.
No, but locks are pretty straightforward to use in python. Use the try: finally: pattern to ensure that a lock is released after you modify your global variable.
There is nothing about globals that makes them any more or less thread safe than any other variables. Whether or not it's possible for an operation to fail or return incorrect results when run in different threads, the best practice is that you should protect data shared between threads.
If I'm reading you right, you're asking if a variable is safe in a single-threaded environment. In this case, where data is not shared between concurrent processes, the variable is safe (after all, there's nothing else running that may interrupt it).
精彩评论