Search code examples
pythonmultithreadingsynchronizationlocking

Shared variable & threading.Lock


In Java, unless you use atomic operations or some other thread sync mechanism, you might have stalled values for a shared variable in a thread.

Given the GIL, in CPython. I see the value of a Lock inc cases where: Multiple steps are taken before assigning a value, even in the confusing a += 1 idiom. To prevent race condition.

But in a case like a = 1, without a Lock. is it possible to have threads A and B reading different values of a after some thread updated it?

Another way of asking this question would be, does Lock ensures shared value propagation and lack of Lock does not?


Solution

  • The issue isn't the a = 1. If the only thing you're doing throughout your code is setting a to various values, then you don't need locks.

    But if at the same time you're setting a = 1, you have somewhere else in your code that's doing a = a + 1, then you need to lock both of them. You're locking a = 1 so that if someone else increments a, it will happen either completely before or completely after you've set a.

    So in almost all cases, unless you really know what you're doing, a lock is the simplest solution.