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

Automatic thread safety for classes


Another useful code snippet...

This allows you to take a non-threadsafe class, and
automatically generate a threadsafe class. When a
method is called for your class, it automatically
locks the object, then calls the method, then unlocks
the object. You will have to perform any further
locking/unlocking manually.

# -------------------------------------------------
# threadclass: Get a threadsafe copy of a class.
# -------------------------------------------------

import types, threading
def threadclass(C):
"""Returns a 'threadsafe' copy of class C.
All public methods are modified to lock the
object when called."""
class D(C):
def __init__(self):
self.lock = threading.RLock()
C.__init__(self)

def ubthreadfunction(f):
def g(self, *args, **kwargs):
self.lock.acquire()
ans = f(self, *args, **kwargs)
self.lock.release()
return ans
return g

for a in dir(D):
f = getattr(D, a)
if isinstance(f, types.UnboundMethodType) and
a[:2] != '__':
setattr(D, a, ubthreadfunction(f))
return D
Example:

class Counter:
def __init__(self):
self.val = 0
def increment(self):
self.val += 1

SafeCounter = threadclass(Counter)
Now SafeCounter is a threadsafe class. Try it out!

Enjoy,
Connelly Barnes

__________________________________
Do you Yahoo!?
New and Improved Yahoo! Mail - 100MB free storage!
http://promotions.yahoo.com/new_mail

Jul 18 '05 #1
1 1378
To properly handle exceptions, the code in the previous posting should
be modified to include a try...finally block:

def ubthreadfunction(f):
def g(self, *args, **kwargs):
try:
self.lock.acquire()
ans = f(self, *args, **kwargs)
finally:
self.lock.release()
return ans
return g

- Connelly
Jul 18 '05 #2

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

Similar topics

4
by: The Crow | last post by:
for example i have static readonly SqlParameter and i want to clone them at runtime. as clone operation will not write to SqlParameter object, just reading, should i lock that object during read...
11
by: dee | last post by:
OleDbCommand class like many .NET classes has the following description in its help file: "Thread Safety Any public static (Shared in Visual Basic) members of this type are safe for...
22
by: Brett | last post by:
I have a second thread, t2, that errors out and will stop. It's status is then "Stopped". I try to start t2 from thread 1, t1, by checking If t2.threadstate = "Stopped" Then t2.start() ...
4
by: Warren Sirota | last post by:
Hi, I've got a method that I want to execute in a multithreaded environment (it's a specialized spider. I want to run a whole bunch of copies at low priority as a service). It works well running...
7
by: intrader | last post by:
I have the following small classes: //----------------code--------------- using System; using System.Collections.Generic; using System.Text; namespace ValidatorsLibrary { public class...
10
by: Paul | last post by:
Hi all, All of the classes in my DAL are static, with constants defining the stored procedures and parameters. I've been having some problems with my site which makes me wonder if there's a...
12
by: Peter K | last post by:
Say I have this class public class Simple { private string name; public string Name { get { return name; } set { name = value; }
2
by: carlos | last post by:
The first application I wrote using asp.net started off rather small, and as a result, the design of the application took a "Rapid Application Development" type of approach. By this I mean that it...
6
by: Olumide | last post by:
Hi - I've got a class that contains static member functions alone, all of whose arguments are passed by reference as shown below: class MySpiffyClass{ // no constructor, destructor or...
13
by: Henri.Chinasque | last post by:
Hi all, I am wondering about thread safety and member variables. If I have such a class: class foo { private float m_floater = 0.0; public void bar(){ m_floater = true; }
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
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...

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.