473,699 Members | 2,087 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 MonitorMetaClas s(type):
def __new__(meta, name, bases, dict):
meta.convert_me thods(dict)
return super(MonitorMe taClass, meta).__new__(m eta, name, bases, dict)

def makeThreadsafeM ethod(func):
def threadsafemetho d(self, *args, **kwargs):
self._monitor_l ockObj.acquire( )
print ">>got lock"
try:
return func(self, *args, **kwargs)
finally:
self._monitor_l ockObj.release( )
print "<<released lock"
return threadsafemetho d
makeThreadsafeM ethod = staticmethod(ma keThreadsafeMet hod)

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.makeThread safeMethod(m)
dict["_monitor_lockO bj"] = RLock()

convert_methods = classmethod(con vert_methods)
class MyClass(object) :
__metaclass__=M onitorMetaClass

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

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

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

Similar topics

3
2588
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 __init__(self): for k in self.__slots__: k = 'something' NewDict = {'__slots__': , '__init__': __init__} for k in ClassDict:
4
1572
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 Stefen Eischet's suggestion for automatically determining a method's type (class/instance/static) from the name of its first formal parameter is a reasonable alternative to any/all of the decorator syntax proposals. Just as the Python system...
39
2919
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 MyMetaclass to keep the order of x,y,z somewhere?
1
2272
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 account a selected list of object attributes) 1. all-in-one metametaclass: class Autohash2(type):
10
1520
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 instances of that class will share the same state, provided that they don't override __new__; otherwise, remember to use Borg.__new__ within the overriden class.
0
8697
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
9184
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9042
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...
0
7759
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4380
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
4634
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3061
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
2
2357
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2013
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.