473,732 Members | 2,204 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

synchronized method


Hi,

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

def synchronized(me thod):

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

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

def wrapper(self, *args):
self.lock.acqui re()
try:
return method(self, *args)
finally:
self.lock.relea se()
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 2787
Max Ischenko wrote:

Hi,

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

def synchronized(me thod):

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

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

def wrapper(self, *args):
self.lock.acqui re()
try:
return method(self, *args)
finally:
self.lock.relea se()
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.u a.remove.it> wrote in message news:<c0******* ***@hyppo.gu.ne t>...
Hi,

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

def synchronized(me thod):

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

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

def wrapper(self, *args):
self.lock.acqui re()
try:
return method(self, *args)
finally:
self.lock.relea se()
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*********@sof tlab.com.ar (Gabriel Genellina) wrote in message news:<94******* *************** ****@posting.go ogle.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.lockObje ct()
object.someFunc 1()
object.someFunc 2()
object.etc()
object.unlockOb ject()

This can sort of be automated a bit by having:

class _SynchronisedMe thod:

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

def __getattr__(sel f,name):
return _SynchronisedMe thod(self._obje ct,"%s.%s"%(sel f._name,name))

def __call__(self,* args):
try:
self._object.lo ckObject()
method = getattr(self._o bject,self._nam e)
result = apply(method,ar gs)
self._object.un lockObject()
except:
self._object.un lockObject()
raise
return result

class _SynchronisedOb ject:

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

def __getattr__(sel f,name):
return _SynchronisedMe thod(self._obje ct,name)

You can then say:

sync_object = _SynchronisedOb ject(object)

sync_object.som eFunc1()
sync_object.som eFunc2()
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.dat aExists():
sync_object.get Data()

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 "synchroniz ed" methods (a-la Java),
could you please check if it is OK:

def synchronized(me thod):

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

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

def wrapper(self, *args):
self.lock.acqui re()
try:
return method(self, *args)
finally:
self.lock.relea se()
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.u a.remove.it> wrote in message news:<c0******* ***@hyppo.gu.ne t>...
Hi,

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

def synchronized(me thod):

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

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

def wrapper(self, *args):
self.lock.acqui re()
try:
return method(self, *args)
finally:
self.lock.relea se()
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******* ********@engcor p.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
14546
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 synchronized objects. However, why couldn't one simply declare: private synchronized LinkedList l; and have the variable be automatically synchronized, instead of having
4
10868
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 cons between those two approaches Thanks a lo Chris
5
29619
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 conclusive... thanks, Scott
6
3735
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 at runtime, the cast of "Queue.Synchronized(new EventQueue())" to an EventQueue object is failing stating invalid cast. Why? public class EventQueue : System.Collections.Queue { ... }
5
4908
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
79887
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 void methodName() {...} What is the C# alternative for this?
4
8190
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 System.Collections.Generic.Queue? Putting it another way can I safely replace a System.Collections.Queue.Synchronized(myUnSynchronizedQueue) with a System.Collections.Generic.Queue while porting a working 2003 project? Thanks,
7
7254
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
2982
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 for Item (this)? Normally,do I need sync at all? Isn't that true without sync the program can run faster?
0
8946
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9307
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9181
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4809
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.