[Python-ideas] Simpler thread synchronization using "Sticky Condition"

Ben Rudiak-Gould benrudiak at gmail.com
Tue Mar 26 18:36:08 EDT 2019


On Tue, Mar 26, 2019 at 2:40 AM Richard Whitehead
<richard.whitehead at ieee.org> wrote:
> Using Python’s Condition class is error-prone and difficult.

After looking at your example, I think the problem is just that you
aren't using condition variables the way they're intended to be used.

To write correct condition-variable code, first write code that
contains polling loops like

    with lock:
        ...
        while not some_boolean_condition():
            lock.release()
            time.sleep(0)
            lock.acquire()
        ...

Then (1) for each boolean condition that you polled on, introduce a
corresponding condition variable; (2) whenever you do something that
causes the truth of that condition to flip from false to true, notify
the condition variable; and (3) replace the polling loop with

        while not some_boolean_condition():
            cvar_associated_with_that_condition.wait()

You should only call Condition.wait() inside a while loop that tests
the associated condition (or use wait_for()). Implementations of
condition variables don't necessarily guarantee that the condition is
true when wait() returns, even if you do everything else correctly.
See https://en.wikipedia.org/wiki/Spurious_wakeup .

If the condition variable is notified when you aren't inside wait(),
you will miss the notification. That isn't a problem because as long
as the boolean condition itself remains true, you will exit the while
loop immediately upon testing it. Or, if the condition has become
false again, you will wait and you will get the next false-to-true
notification. Condition variables are not meant to substitute for
polling the actual condition; they just make it more efficient.


More information about the Python-ideas mailing list