Automatic thread safety

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Connelly Barnes

    Automatic thread safety

    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 ubthreadfunctio n(f):
    def g(self, *args, **kwargs):
    self.lock.acqui re()
    ans = f(self, *args, **kwargs)
    self.lock.relea se()
    return ans
    return g

    for a in dir(D):
    f = getattr(D, a)
    if isinstance(f, types.UnboundMe thodType) and a[:2] != '__':
    setattr(D, a, ubthreadfunctio n(f))
    return D


    Example:

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

    SafeCounter = threadclass(Cou nter)


    Now SafeCounter is a threadsafe class. Try it out!

    Enjoy,
    Connelly Barnes
  • Peter Hansen

    #2
    Re: Automatic thread safety

    Connelly Barnes wrote:
    [color=blue]
    > Another useful code snippet...[/color]
    [snip]

    The Python Cookbook at http://aspn.activestate.com/ASPN/Python/Cookbook/
    would be a much more effective way to make these snippets available
    to others.

    Comment

    Working...