tantuni
tantuni

Reputation: 689

locking global variables under the Threading module of python

Let us suppose I have 2 threads and a single global variable in a python code with the threading module. In this code, only thread-1 modifies the global variable's value, whereas, thread-2 only reads the value of the global variable and perform its task depending on that value.

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

Upvotes: 4

Views: 7758

Answers (1)

Esme Povirk
Esme Povirk

Reputation: 3164

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

If the global variable is a mutable object, like a list, and you are modifying that object, it depends on the method you use. Most methods on builtin objects like lists are atomic.

I can't say for sure that you don't need a lock, though, without knowing more details about the purpose of that variable and how you are using it. Why does thread-2 need to change its behavior based on that value, and is it OK if thread-1 changes the value just after thread-2 has made its decision? If it's not OK, you may still need a lock.

(An analogous situation in C - assigning a value to a pointer variable - is also atomic under normal circumstances, though pointer assignments can be reordered. You can use this in some circumstances to avoid locks in C.)

Upvotes: 15

Related Questions