Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 1000
Carson Avatar asked Feb 11 '10 22:02

Carson


People also ask

Are global variables thread-safe?

4 Replies. Hello, Your global variable are not thread safe.

Should you avoid using global variables in Python?

While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.

Are global variables shared by threads?

Threads share all global variables; the memory space where global variables are stored is shared by all threads (though, as we will see, you have to be very careful about accessing a global variable from multiple threads). This includes class-static members!

Is Python threading thread-safe?

Python is not by its self thread safe. But there are moves to change this: NoGil, etc. Removing the GIL does not make functions thread-safe.


1 Answers

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.

like image 83
Thomas Wouters Avatar answered Sep 28 '22 00:09

Thomas Wouters