473,395 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

synchronized method


Hi,

I wrote simple implementation of the "synchronized" methods (a-la Java),
could you please check if it is OK:

def synchronized(method):

"""
Guards method execution, similar to Java's synchronized keyword.

The class which uses this method, is required to have a
L{threading.Lock} primitive as an attribute named 'lock'.
"""

def wrapper(self, *args):
self.lock.acquire()
try:
return method(self, *args)
finally:
self.lock.release()
return wrapper

....I'm no big thread expert

tia.

.... The problem is not that there are problems. The problem is expecting
otherwise and thinking that having problems is a problem.
-- Theodore Rubin
Jul 18 '05 #1
5 2774
Max Ischenko wrote:

Hi,

I wrote simple implementation of the "synchronized" methods (a-la Java),
could you please check if it is OK:

def synchronized(method):

"""
Guards method execution, similar to Java's synchronized keyword.

The class which uses this method, is required to have a
L{threading.Lock} primitive as an attribute named 'lock'.
"""

def wrapper(self, *args):
self.lock.acquire()
try:
return method(self, *args)
finally:
self.lock.release()
return wrapper

...I'm no big thread expert

tia.

... The problem is not that there are problems. The problem is expecting
otherwise and thinking that having problems is a problem.
-- Theodore Rubin


I'd add **kwargs too.

anton.
Jul 18 '05 #2
Max Ischenko <ma*@ucmg.com.ua.remove.it> wrote in message news:<c0**********@hyppo.gu.net>...
Hi,

I wrote simple implementation of the "synchronized" methods (a-la Java),
could you please check if it is OK:

def synchronized(method):

"""
Guards method execution, similar to Java's synchronized keyword.

The class which uses this method, is required to have a
L{threading.Lock} primitive as an attribute named 'lock'.
"""

def wrapper(self, *args):
self.lock.acquire()
try:
return method(self, *args)
finally:
self.lock.release()
return wrapper
Under normal execution the lock will not be released because you return
from the try clause. There is also the case that method isn't defined.

Someone else was asking about this sort of thing back the end of January.
The post is included below. As much as doing this sort of thing may sound
like a good way of handling synchronisation, it still has its problems.

ga*********@softlab.com.ar (Gabriel Genellina) wrote in message news:<94**************************@posting.google. com>... Hello!

I have a number of objects that are not thread-safe - no locking
mechanism was originally provided.
But I want to use them in a thread-safe way. I don't want to analyze
each class details, looking for where and when I must protect the
code. So I wrote this sort-of-brute-force locking mechanism using
threading.RLock() around __getattr__ / __setattr__ / __delattr__.
The idea is that *any* attribute and method access is protected by the
lock. The calling thread may acquire the lock multiple times, but
other threads must wait until it is released.
This may be too much restrictive, and a bottleneck in performance,
since *all* accesses are effectively serialized - but it's the best I
could imagine without deeply analyzing the actual code.
I *think* this works well, but since I'm not an expert in these
things, any comments are welcome. Specially what could go wrong, if
someone could anticipate it.
Note: As written, this only works for old-style classes. I think that
just by adding a similar __getattribute__ would suffice for new-style
classes too - is that true?


A few problems that I can see. First is that this only protects access to
the reference to the data in question. Imagine that the data value
is a dictionary. If I understand it correctly, two different threads
could still get a reference to the same dictionary and then independently
start modifying the dictionary at the same time. This is because you are
then dealing with the dictionary directly and your locks aren't involved
at all.

Second is that it isn't always sufficient to lock at the level of individual
attributes, instead it sometimes necessary to lock on a group of attributes
or even the whole object. This may be because a thread has to be able
to update two attributes at one time and know that another thread will
not change one of them while it is modifying the other.

One hack I have used is always ensuring that access to an object is
through its functional interface and then locking at the level of
function calls. That is provide additional member functions called
lockObject and unlockObject which operate the thread mutex. When
using the class then have:

object.lockObject()
object.someFunc1()
object.someFunc2()
object.etc()
object.unlockObject()

This can sort of be automated a bit by having:

class _SynchronisedMethod:

def __init__(self,object,name):
self._object = object
self._name = name

def __getattr__(self,name):
return _SynchronisedMethod(self._object,"%s.%s"%(self._na me,name))

def __call__(self,*args):
try:
self._object.lockObject()
method = getattr(self._object,self._name)
result = apply(method,args)
self._object.unlockObject()
except:
self._object.unlockObject()
raise
return result

class _SynchronisedObject:

def __init__(self,object):
self._object = object

def __getattr__(self,name):
return _SynchronisedMethod(self._object,name)

You can then say:

sync_object = _SynchronisedObject(object)

sync_object.someFunc1()
sync_object.someFunc2()
sync_object.etc()

Although this avoids the explicit calls to lock the object, it still isn't the
same thing. This is because in the first example, the lock was held across
multiple function calls whereas in the second case it is only held for a
single call. Thus something like the following could fail:

if sync_object.dataExists():
sync_object.getData()

This is because something could have taken the data between the time
the check for data was made and when it was obtained.

Thus automating it like this isn't foolproof either. The closest you will
probably get to a quick solution is to have the lock/unlock functions
for the object and change any code to use them around any sections of
code which you don't want another thread operating on the class at
the same time. You may even have to hold locks on multiple objects
at the same time to ensure that things don't get stuffed up.

Thus it isn't necessarily a simple task to add threading support after
the fact. You probably will have no choice but to analyse the use of
everything and work out to correctly implement locking or even change
the functional interface a bit so functions can be atomic in themselves.
Ie., rather than having to check if data exists before first getting it,
you just try and get it and either rely on an exception or have the
thread wait until data is there.
Jul 18 '05 #3
Graham Dumpleton wrote:
I wrote simple implementation of the "synchronized" methods (a-la Java),
could you please check if it is OK:

def synchronized(method):

"""
Guards method execution, similar to Java's synchronized keyword.

The class which uses this method, is required to have a
L{threading.Lock} primitive as an attribute named 'lock'.
"""

def wrapper(self, *args):
self.lock.acquire()
try:
return method(self, *args)
finally:
self.lock.release()
return wrapper

Under normal execution the lock will not be released because you return
from the try clause.


Hmm. I think you must be wrong:
def foo(): try:
return 1
finally:
print 'ok'

foo()

ok
1
There is also the case that method isn't defined.
Indeed, thanks for pointing this out.
Someone else was asking about this sort of thing back the end of January.
The post is included below. As much as doing this sort of thing may sound
like a good way of handling synchronisation, it still has its problems.


[ cut ]

I'll look into it.
Jul 18 '05 #4
Graham Dumpleton wrote:

Max Ischenko <ma*@ucmg.com.ua.remove.it> wrote in message news:<c0**********@hyppo.gu.net>...
Hi,

I wrote simple implementation of the "synchronized" methods (a-la Java),
could you please check if it is OK:

def synchronized(method):

"""
Guards method execution, similar to Java's synchronized keyword.

The class which uses this method, is required to have a
L{threading.Lock} primitive as an attribute named 'lock'.
"""

def wrapper(self, *args):
self.lock.acquire()
try:
return method(self, *args)
finally:
self.lock.release()
return wrapper


Under normal execution the lock will not be released because you return
from the try clause. There is also the case that method isn't defined.


If that were true, the finally clause would be pretty useless in many
cases. (Try it out yourself: it will work properly.)

Also, isn't "method" defined as the argument to the synchronized()
function at the top?

To me, this looks like a pretty reasonable approach to handling
the problem as defined.

-Peter
Jul 18 '05 #5
Peter Hansen <pe***@engcorp.com> wrote in message news:<40***************@engcorp.com>...
Under normal execution the lock will not be released because you return
from the try clause. There is also the case that method isn't defined.


If that were true, the finally clause would be pretty useless in many
cases. (Try it out yourself: it will work properly.)

Also, isn't "method" defined as the argument to the synchronized()
function at the top?


Hmmm, I stand corrected on both counts. It was one of the days I should
have kept my mouth shut. Too stinking hot here at the moment, my brain
isn't working. :-)
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Frank | last post by:
Hi, In the javadocs regarding many of the java.util classes, it states that the classes are not synchronized, and suggest using the Collections.synchronizedX(...) methods for getting...
4
by: chrisben | last post by:
Hi I often use Queue.Synchronized method to create a queue for multithread writing. I also know I could use SyncRoot and lock to write Queue. Could anyone here please explain to me the pros and...
5
by: Seeker | last post by:
Hello, I've read conflicting posts about . Does it or does it not lock the entire object? In my simple test it appears to block just the method but I wouldn't exactly call my meager test...
6
by: rmunson8 | last post by:
I have a derived class from the Queue base class. I need it to be thread-safe, so I am using the Synchronized method (among other things out of scope of this issue). The code below compiles, but...
5
by: norbert.thek | last post by:
Hi Can somebody tell me if I'm right or not The attribute Is like an lock(this) over the Method where i put this Attribute?! If I have two methods like:
8
by: ASP.Net programmer | last post by:
Hi, I have a few methods in a class that I want to synchronize (make sure they can't be used at the same time by multiple threads). As a Java programmer I just do this: public synchronized...
4
by: nhmark64 | last post by:
Hi, Does System.Collections.Generic.Queue not have a Synchronized method because it is already in effect synchronized, or is the Synchronized functionality missing from...
7
by: Alan Wang | last post by:
Hi there, How can I create synchronized method in vb.net like synchronized method in Java? Thanks in advanced Alan
3
by: Ryan Liu | last post by:
Hi, What does ArrayList.Synchronized really do for an ArrayList? Is that equal to add lock(this) for all its public methods and properties? Not just for Add()/Insert()/Remvoe()/Count, but also...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.