Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > metaclass to create a thread-safe class ("monitor"), allright?

Thread Tools

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

Irmen de Jong
Posts: n/a
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:
>>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

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Metaclass of a metaclass Steven D'Aprano Python 1 06-05-2012 03:30 PM
Add methods to a predefined class: on the class instance or metaclass? Eustaquio Rangel de Oliveira Jr. Ruby 4 07-05-2005 04:14 PM
metaclass that inherits a class of that metaclass? ironfroggy Python 16 06-03-2005 10:00 AM
Metaclass to make all methods of a class thread-safe Irmen de Jong Python 5 09-28-2004 06:01 PM
circular dependency between class and its metaclass Stefan Seefeld Python 1 01-19-2004 08:02 AM