syam
syam

Reputation: 397

variable locking in python thread fails to lock if multiple lock instance created?

I am new to threads and having a question..

from threading import Thread, Lock
s=0
lock =Lock()  ---->lock object position
def sample():
global s
for i in range(10000):
    lock.acquire()
    s+=1
    lock.release()    
t1 = Thread(target=sample)
t2 = Thread(target=sample)
t1.start()
t2.start()
t1.join()
t2.join()
print s

This code gives expected result of 20000 as the operation on variable s is done atomically.

But when I change the lock() creation position, the locks are not working as expected. I changed like

 from threading import Thread, Lock
    s=0    
    def sample():
        lock =Lock()  ---> lock() added inside function
        global s
        for i in range(10000):
            lock.acquire()
            s+=1
            lock.release()    
    t1 = Thread(target=sample)
    t2 = Thread(target=sample)
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    print s

With this change I am getting inconsistent values. So I am guessing the lock is not working here. Can some one help me to understand lock working based on this example?
Do locking only get honored if same lock object is used for both threads?

TIA

Upvotes: 0

Views: 825

Answers (1)

selbie
selbie

Reputation: 104514

In your first version, the Lock is created before the threads are ever started and is a global variable available to both thread. Hence, this single lock object is shared between the threads. The lock object will only allow one thread at a time to acquire it. While it's been acquired, the other thread invoking .acquire() will block until the other thread invokes .release(). And as you noted, your code works as expected.

In your second version, when you move the Lock creation into the thread function as a local variable. Hence, each thread invokes a different run of sample which creates a unique and different lock object. Each thread is always able to acquire the local lock variable without waiting because the other thread is always acquiring another lock. Hence, the s variable isn't really protected.

Upvotes: 1

Related Questions