Reputation: 281
I wanted to ask a question regarding the following code: suppose we wanted to build a threading.Thread
subclass ThreadCounter
, such that it has as arugment a name, an initial value and a terminal value and once started it increments the initial value up until it is equal to the terminal one.
import threading
from threading import Thread
import time
lock = threading.Lock()
class ThreadCounter(Thread):
def __init__(self, nome, first, limit, lock):
# Call the Thread class's init function
Thread.__init__(self)
self.nome = nome
self.first = first
self.limit = limit
self.lock = lock
# Override the run() function of Thread class
def run(self):
while self.first < self.limit:
self.lock.acquire()
self.first += 1
print(self.nome,self.first)
time.sleep(3)
self.lock.release()
t1 = ThreadCounter('Thread-1', 1, 5, lock)
t2 = ThreadCounter('Thread-2', 2, 10, lock)
t1.start()
t2.start()
t1.join()
t2.join()
I do not understand what happens when we are using the locks in the two classes. In particular, are we assigning the same lock-object to both of the instances with the assignment
t1 = ThreadCounter('Thread-1', 1, 5, lock)
t2 = ThreadCounter('Thread-2', 2, 10, lock)
Or we have a different lock object for every occurence of the ThreadCounter class, such that t1 and t2 do not share the same lock?
Upvotes: 0
Views: 808
Reputation: 45826
It's the same lock. It would defeat the purpose of locking if each thread had its own lock.
The purpose of locks is to synchronize the two threads to ensure that they aren't executing critical sections at the same time. In this case, the only thing it's effectively locking is print
, but if the two threads were manipulating a shared resource like a list, the lock would ensure that only one thread is touching the list at a time. This is required since most objects are not safe to operate on across threads at the same time ("non-thread-safe").
Look into "synchronization primitives" to understand what the different synchronization options are, and why they're necessary.
Upvotes: 1