Locking global variables in threading python module

Suppose I have 2 threads and one global variable in python code with a streaming module. In this code, only thread-1 changes the value of the global variable, while thread-2 only reads the value of the global variable and performs its task depending on this value.

In this situation, do I need to protect access to a global variable with Lock ()? In C, a mutex should be used in this condition. However, what about python with the GIL? Is that still the case? Is lock () required?


source to share

1 answer

Assigning an object's value to a global variable is an atomic operation in Python. Other threads cannot read the variable incorrectly by reading it while it is assigned. The GIL guarantees this in Python's C implementation, but other implementations can and do this in different ways.

If the global variable is a mutable object, such as a list, and you modify that object, it depends on the method you are using. Most of the methods of built-in objects, such as lists, are atomic.

I can’t say for sure that you don’t need a lock without knowing the details about the purpose of this variable and how to use it. Why should thread-2 change its behavior based on this value, and is it okay for thread-1 to change the value right after thread-2 has made a decision? If this is not the case, you may need a lock.

(A similar situation in C β€” assigning a value to a pointer variable β€” is also atomic under normal circumstances, although pointer assignments can be reordered. You can use this in some cases to avoid locks in C.)



All Articles