472,102 Members | 1,983 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

metaclass to create a thread-safe class ("monitor"), allright?

I created my first ever Python Meta Class to solve a
problem I'm having. I have an existing class that I want
to make thread-safe: all method calls should use a thread-lock
to avoid having multiple threads active in the class at the
same time. I don't want to change every method of the class
by adding lock.acquire()...try...finally..lock.release() stuff,
so I decided to try it with a Meta Class.

Below is what I came up with (after a bit of googling).

Since it's my first attempt at a non-trivial meta class,
can you please comment on it? Is this the way to do things?

It appears to work, at least the example method call at the
bottom prints:
[E:\]python meta.py
got lock

irmen 42
<<released lock

which is what I wanted..

Irmen de Jong.
#----------Code follows-----------
from types import FunctionType
from threading import RLock

class MonitorMetaClass(type):
def __new__(meta, name, bases, dict):
return super(MonitorMetaClass, meta).__new__(meta, name, bases, dict)

def makeThreadsafeMethod(func):
def threadsafemethod(self, *args, **kwargs):
print ">>got lock"
return func(self, *args, **kwargs)
print "<<released lock"
return threadsafemethod
makeThreadsafeMethod = staticmethod(makeThreadsafeMethod)

def convert_methods(cls, dict):
methods=[ v for k,v in dict.iteritems() if isinstance(v, FunctionType) ]
for m in methods:
dict["_monitor_lockObj"] = RLock()

convert_methods = classmethod(convert_methods)
class MyClass(object):

def method(self, a1, a2):
print a1,a2

Jul 18 '05 #1
0 1144

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by achan | last post: by
4 posts views Thread by Paul Morrow | last post: by
39 posts views Thread by Nicolas Fleury | last post: by
1 post views Thread by Antoine Pitrou | last post: by
10 posts views Thread by =?iso-8859-1?B?QW5kcuk=?= | last post: by
reply views Thread by leo001 | last post: by

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.