473,397 Members | 1,974 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,397 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):
meta.convert_methods(dict)
return super(MonitorMetaClass, meta).__new__(meta, name, bases, dict)

def makeThreadsafeMethod(func):
def threadsafemethod(self, *args, **kwargs):
self._monitor_lockObj.acquire()
print ">>got lock"
try:
return func(self, *args, **kwargs)
finally:
self._monitor_lockObj.release()
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[m.__name__]=cls.makeThreadsafeMethod(m)
dict["_monitor_lockObj"] = RLock()

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

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

m=MyClass()
m.method("irmen",42)
Jul 18 '05 #1
0 1202

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

Similar topics

3
by: achan | last post by:
As I was trying to create a metaclass, I found out that __init__ defined in it does not initializes at all: class CMeta(type): def __new__(cls, ClassName, BaseClass, ClassDict): def...
4
by: Paul Morrow | last post by:
One of the beautiful things about Python is its clear, minimal syntax. So we must resist adding new syntax to the language, especially where there is a reasonable alternative. I believe that...
39
by: Nicolas Fleury | last post by:
In the following example: class MyMetaclass(type): pass class MyBaseType(object): __metaclass__ = MyMetaclass class MyType(MyBaseType): x = 4 y = 5 z = 6 Is there any way to modify...
1
by: Antoine Pitrou | last post by:
Hi, I've been looking at writing parameterized metaclasses and here are the two solutions I've come to: (my goal was to build a way to automatically add a hash function that would take into...
10
by: =?iso-8859-1?B?QW5kcuk=?= | last post by:
In my application, I make use of the Borg idiom, invented by Alex Martelli. class Borg(object): '''Borg Idiom, from the Python Cookbook, 2nd Edition, p:273 Derive a class form this; all...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.