I want to create a synchronized method in python with respect to some CRUD functions on all instances of a class. For example while create is called and ongoing by a thread, delete needs to wait on the same object.
Can someone please tell me if the code below is correct. I may have some syntax error but what I want to know is if the lock is going to be the same across calls to create ALL instances of this class and therefore if any instance create/delete is in progress delete/create on the same or other instances by another thread will have to wait?
import threading
import functools
def synchronized(wrapped):
lock = threading.Lock()
@functools.wraps(wrapped)
def _wrap(*args, **kwargs):
with lock:
return wrapped(*args, **kwargs)
return _wrap
class AtomicCRUD(object):
@synchronized
def create(self):
#Do stuff that may take a while here.
pass
@synchronized
def delete(self):
#Do stuff that may take a while here.
pass
My understanding of python is synchronized will be called for each of create/delete function object. I put a print statement in the synchronized function above for the lock object and did a test run using the following:
@synchronized
def test1():
print "test1"
@synchronized
def test2():
print "test2"
And I get the following output, which makes me think the lock used is the same for both function objects. I don't seem to understand how this works.
<Semaphore c=1 _w[0]>
<Semaphore c=1 _w[0]>
test1
test2