views:

550

answers:

3

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 collision and the wrong value being returned to the wrong thread?

+2  A: 

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.

Thomas Wouters
are you saying that any function or class method with `x += 1` is not thread-safe?
Carson
A: 

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).

Daniel G
+1  A: 

Assuming MongoEngine is wrapping PyMongo (and I believe it is), then you should be fine. PyMongo is completely thread-safe.

mdirolf
yes, it wraps pymongo, but stores the pymongo.Connection instance in a global variable
Carson
That's fine then - it's safe to share a Connection instance.
mdirolf