473,320 Members | 1,839 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,320 software developers and data experts.

Synchronizing methods of a class

Hello to all fellow c.l.p'ers!

Long-time listener, first-time caller.

Background:
I'm working on a project where I have to do some serious
multithreading. I've worked up a decorator in Python 2.3.4 to implement
the lock semantics required for specific functions I want to
synchronize:

def synchronized(method):
def f(*args,**kwargs):
self = args[0]
self._lock.acquire();
try:
return method(*args,**kwargs)
finally:
self._lock.release()
return f

And a convenience method to synchronize all methods of a given class:

def synchronize(klass, allow=None, deny=None):
"""Synchronize methods in the given class
Only synchronize the methods whose names are
not in the deny list,in the allow list, or all methods if allow and
deny are not specified.."""
if deny is None: deny=[]
deny.append('__init__')
for (name, val) in klass.__dict__.items():
print "attr '%s':" % (name),
if callable(val):
if name not in deny:
if allow is None or name in allow:
klass.__dict__[name] = synchronized(val)
print "synchronized."
else:
print "not synchronizing, name not in allow list" % name
else:
print "not synchronizing, name in deny list."
else:
print "not synchronizing, not callable."
return klass

Obviously, my classes have to instantiate the _lock in __init__ in
order for this to work.

Problem:

When iterating through klass.__dict__.items() in the convenience
method, I only get the instance variables of the class. No functions.
I've found a way to get the function list, by iterating through
klass.__class__.__dict__ .

My Question:

If I decorate these function references in __class__.__dict__, am I
doing it only for my specific instance of that class or the base class
as well?

Thanks in advance,
Keith Veleba

Jul 18 '05 #1
3 2514
> My Question:

If I decorate these function references in __class__.__dict__, am I
doing it only for my specific instance of that class or the base class
as well?


A class is a class - so yes, all instances are affected. You might want to
think about metaclasses for decorating.
--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
On Mon, Feb 07, 2005 at 11:57:02AM -0800, Keith Veleba wrote:
Background:
I'm working on a project where I have to do some serious
multithreading. I've worked up a decorator in Python 2.3.4 to implement
the lock semantics required for specific functions I want to
synchronize:
I found Chris Liechti's example very helpful when working on a similar
project. See
http://groups-beta.google.com/group/...47a830de39d1db
.. Also, I strongly suggest using threading.RLock() objects instead of primitive
locks. With Rlocks one thread can acquire the same lock multiple times without
blocking. This is useful if one synchronized method calls another synchronized method.
Obviously, my classes have to instantiate the _lock in __init__ in
order for this to work.
The great thing about Chris's example is that the first time a synchronized
method is called a lock is instantiated, so you don't have to worry about this
step.
Problem:

When iterating through klass.__dict__.items() in the convenience
method, I only get the instance variables of the class. No functions.
I've found a way to get the function list, by iterating through
klass.__class__.__dict__ .


I'm not sure why klass.__dict__.items() isn't working for you. I tried a simple
example:

class simple(object):
def hello(self):
print "Hello World"

def methods(cls):
for name,value in cls.__dict__.items():
if callable(value):
print name
methods(simple)

hello
Chris
Jul 18 '05 #3
Chris,

Q&D example of <<class>>.__dict__.items() not working for me:
import threading
class A(threading.Thread): .... def __init__(self):
.... threading.Thread.__init__(self)
.... def one(self):
.... pass
.... def two(self):
.... pass
.... a = A()
a.__dict__.items()

[('_Thread__block',
<Condition(<thread.lock object at 0x009BE070>, 0)>),
('_Thread__name', 'Thread-1'),
('_Thread__daemonic', False),
('_Thread__started', False),
('_Thread__target', None),
('_Thread__kwargs', {}),
('_Verbose__verbose', False),
('_Thread__args', ()),
('_Thread__stopped', False),
('_Thread__initialized', True)]

Neither function I added to the A class shows up.

However, I think it's because I'm using an instance of my class vs.
just referencing the class type.

If I type:

A.__dict__items()

I get the correct list:

[('__module__', '__main__'),
('__doc__', None),
('two', <function two at 0x009E21B0>),
('__init__', <function __init__ at 0x009E2170>),
('one', <function one at 0x009E2230>)]

In any case, thanks for the example reference. That's helps me improve
my idea, and I will most likely use the methods in it.

Keith

Jul 18 '05 #4

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

Similar topics

99
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less...
18
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I...
6
by: Allen Jones | last post by:
Hi, I tried to extend ListDictionary in order to create a thread safe version named SynchronizedListDictionary. Despite the docs saying the properties and methods of ListDictionary are...
2
by: Chuck | last post by:
I have not been able to find a good answer about the System.Collections.Queue.Synchronized() method and how it actually works or is to be used. If I create my Queue in the following manner: ...
2
by: Christopher D. Wiederspan | last post by:
We are getting ready to move an ASP.NET application off of a single development machine and onto a "webfarm". Basically our webfarm is a bunch of identical servers with the load-balancing provided...
4
by: MaxMax | last post by:
I'm using HttpWebRequest. It seems that all the callback called from HttpWebRequest are in another thread (not in the "original" thread). Now my problem is that the "original" thread is the thread...
3
by: javelin | last post by:
Does anyone have any suggestions for synchronizing multiple websites? We have a dev server, a testing server, and a live server. Now, we have 3 developers, and we are having trouble tracking...
8
by: colin | last post by:
Hi, this probaly isnt the most relevant place to ask this, but Im using a windows forms in c# timer to process user input and invalidate a window if its changed. Im having problems in that the...
2
by: fgh.vbn.rty | last post by:
Hi, I'm not sure if i'm asking the question correctly but anyway here it is. Say I have 3 classes - class A, class B, class R. 1) A and B are the building blocks and R is like a repository...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.