Dispatching caught exceptions

Gerson Kurz gerson.kurz at t-online.de
Fri Dec 6 05:41:45 EST 2002


I've written a small mixin class that can be used to synchronize
member function calls by enclosing the actual function call in a
mutex acquire/release block. The class reads as follows:
    
----------------- (snip here) --------------------

import threading, traceback

class ThreadSafeMixinClass:
    def __init__(self):
        self.mutex = threading.Semaphore()

    def synchronize(self, function_name):
        function_to_be_called = getattr( self, function_name )

        def closure_function( *arguments, **keywords ):
            result = None
            self.mutex.acquire()
            try:
                result = apply(function_to_be_called, arguments,
keywords)
            except:
                traceback.print_exc()
            self.mutex.release()
            return result
        
        setattr(self, function_name, closure_function)

----------------- (snip here) --------------------

Example usage would be:
    
----------------- (snip here) --------------------

class SampleClass(ThreadSafeMixinClass):
    def __init__(self):
        ThreadSafeMixinClass.__init__(self)
        self.synchronize("test")

    def test(self, arg1, arg2, arg3):
        print "test called using %s, %s, %s" % (arg1, arg2, arg3)

----------------- (snip here) --------------------
Now, the "test" function can be called from many threads at the same
time. 

So far, so good. 

Why do I enclose apply in a try/except block? Because otherwise a
deadlock could occur if one thread catches an exception but does not
release the blocking mutex. 

OK, but sometimes I want a thus synchronized function to throw an
exception anyway? What I'm looking for thus is something like

try:
	...
except anything:
	# store exception "anything" somewhere
self.mutex.release()
raise exception

This seems like really simple stuff, but I cannot find it. (Maybe
because I don't like exceptions anyway?)





More information about the Python-list mailing list