Automatic thread safety for classes

C

C. Barnes

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
 
C

Connelly Barnes

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,798
Messages
2,569,651
Members
45,384
Latest member
GOLDY

Latest Threads

Top