[Python-Dev] Proposed addition to threading module - released

Tim Peters tim.peters at gmail.com
Mon Apr 24 21:10:29 CEST 2006


[Guido]
> Actually, what Nick describes is *exactly* how one should write code
> using a condition variable:
>
>   LOCK
>   while nothing to do:
>       UNLOCK
>       wait for the condition variable (or sleep, or whatever)
>       LOCK
>   # here we have something to do with the lock held
>   remove the to-do item
>   UNLOCK
>
> except that the outer LOCK/UNLOCK pair should be using a try/except
> and the inner UNLOCK/LOCK pair should too. I don't see how you can do
> this easily by rewriting the code; the rewrite would be considerably
> ugly (or requires a GOTO :-).

That didn't make much sense to me.  If you're using a condition
variable `cv`, the way that should be written is:

    cv.acquire()
    try:
        while nothing to do:
            cv.wait()   # which unlocks on entry, and locks before return
        do something
    finally:
        cv.release()

IOW, there is no "inner UNLOCK/LOCK" for the user to worry about
(although the implementation of wait() has to worry about it).

Does

    with cv:

work to replace the outer (== only) acquire/try/finally/release dance?
 If so, that seems like plenty to me.


More information about the Python-Dev mailing list