Shao Kahn
Shao Kahn

Reputation: 77

Python -- If a lock is acquired in a thread, are all variables in this thread locked?

import threading

v = 0
lock = threading.Lock()

def increment():
  global v
  v += 1
  lock.acquire()

def decrement():
  global v
  v -= 1

thread1 = threading.Thread(target = increment)
thread2 = threading.Thread(target = decrement)
thread1.start()
thread2.start()
print(v)

This code prints 0,thread2 works normally. Thread1 obviously acquired the lock, why can thread2 also manipulate the global variable v?

Upvotes: 1

Views: 3410

Answers (1)

Phil
Phil

Reputation: 130

Acquiring a lock does not prevent anyone from accessing anything. It is just a contract that critical parts of code can check if they are allowed to access an object. This must be implemented in your code. Simple example:

# Thread 1
lock.acquire() # blocks if someone else locked first
# access "protected" object here
lock.release() # give someone else the opportunity to lock


#Thread 2
lock.acquire() # blocks if someone else locked first
# access "protected" object here
lock.release() # give someone else the opportunity to lock

So for your example and with using a contextmanager to automatically lock and release the lock you get something like:

import threading

v = 0
lock = threading.Lock()

def increment():
    global v
    with lock:
        v += 1

def decrement():
    global v
    with lock:
        v -= 1

...

Upvotes: 1

Related Questions