I have a little threading / locking dilema. I am trying to achieve something like this:
import threading
import time
class A:
def __init__(self):
self.lock = threading.Lock()
def print_stuff(self):
with self.lock:
## do some hazard with stuff !
print("OK")
def other_function(self):
with self.lock:
## some more hazard stuff
pass
def worker(a):
while alive:
"""thread worker function"""
a.print_stuff()
a = A()
alive = True
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(a,))
threads.append(t)
t.start()
try:
while True:
pass
except KeyboardInterrupt:
alive = False
print('interrupted!')
There is a class A - collection of functions mainly, but with some properties also. It will be use for communication with other devices via HTTP or different protocol.
My idea is to lock every function to prevent two functions of A instance being called at the same time. To my surprise, it works without lock also, but so far I am not doing anything hazardous in the functions.
My questions:
Is the implemented lock sufficient enough to prevent any touch of the same resources by multiple threads (the workers will only call functions, they will not touch the properties of A instance)?
Is it better to make the lock global and lock the function directly in worker (instead in the A instance)? See example:
lock = threading.Lock()
def worker(a):
while alive:
"""thread worker function"""
with lock:
a.print_stuff()