[issue21913] Possible deadlock in threading.Condition.wait() in Python 2.7.7

Josh Rosenberg report at bugs.python.org
Fri Jul 4 03:32:58 CEST 2014


Josh Rosenberg added the comment:

So you want it to raise the same exception that is raised in Python 3.4? Either way, I don't think this is a deadlock (to get a deadlock, you'd have to have contested locks; this lock is being acquired only once). You're explicitly violating the rules of using Conditions.

To be precise, you:

1. Acquire the Condition's lock in the main thread (legal, if odd to do in the constructor)
2. Call the Condition's wait method (legal; you acquired the lock so you can wait)
3. (Implicit) By wait-ing, you implicitly release the lock
4. At some point, you hit Ctrl-C. If the signal handler is called as expected, it will try to call Condition.notify(), which is illegal, because the lock was released as a side-effect of calling Condition.wait() earlier.

So best case scenario, this code is wrong. The fact that it doesn't work correctly in Python 2.7 is an issue, but the possible reasons go well beyond deadlocks; you've written code that is guaranteed to be wrong (throw RuntimeExceptions) even if all goes according to plan.

Do you get more reasonable behavior if you write the class as:

class A:
    def __init__(self):
        self._termination_signal = Condition()

    def _signal_handler(self, signum, frame):
        print "Received terminate request - signal = {0}".format(signum)
        del frame
        with self._termination_signal:
            self._termination_signal.notify()

    def register_and_wait(self):
        with self._termination_signal:
            signal(SIGINT, self._signal_handler)
            signal(SIGTERM, self._signal_handler)
            signal(SIGQUIT, self._signal_handler)
            print "Waiting to be interrupted!"
            self._termination_signal.wait()      # control blocks here!
        print "Notified!!"

----------
nosy: +josh.rosenberg

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue21913>
_______________________________________


More information about the Python-bugs-list mailing list