By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,639 Members | 1,988 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,639 IT Pros & Developers. It's quick & easy.

Automatic thread safety

P: n/a
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()

def ubthreadfunction(f):
def g(self, *args, **kwargs):
ans = f(self, *args, **kwargs)
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

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!

Connelly Barnes
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply

P: n/a
Connelly Barnes wrote:
Another useful code snippet...


The Python Cookbook at
would be a much more effective way to make these snippets available
to others.
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.