Are Python global variables thread safe?

edit: im asks if global variables are safe in single-threaded web infrastructure like tornadoes

im using mongoengine orm, which gets the global variable database connection:

_get_db() # gets the db connection 

im also uses tornado, a python single threaded web infrastructure. in one specific 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 global var, is there a chance of a collision and the wrong value returns to the wrong stream?

+4
source share
4 answers

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

+2
source

When interacting with Python objects, you always need to hold the GIL. The namespace in which the variables are stored is a Python object (either a frame object or a dict, depending on which variable). It is always safe to get or set variables in multiple threads. You will never get garbage data.

However, the usual race conditions apply to which object you receive or which object you replace at the time of appointment. An operator of type x += 1 not thread safe, because another thread can run between it and the store, changing the value of x , which you then overwrite.

+3
source

No, but locks are pretty easy to use in python. Use the try: finally: pattern to ensure that the lock is released after the global variable is changed.

+1
source

There is nothing about a global value that makes them more or less thread safe than any other variable. Regardless of whether the operation can fail or return incorrect results when working in different threads, it is best to use the protection of data shared between threads.

If I read you correctly, you ask if the variable is safe in a single-threaded environment. In this case, when the data is not shared between parallel processes, the variable is safe (in the end, nothing works there, which can interrupt it).

0
source

Source: https://habr.com/ru/post/1301055/


All Articles