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

"Martin v. Löwis" martin at v.loewis.de
Tue Apr 25 01:03:46 CEST 2006


Guido van Rossum wrote:
> 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 :-).

I thought the trick is that the condition variable *atomically*
releases the lock, waits for the condition, and then reacquires
the condition variable. I.e.

c = threading.Condition()
c.lock()
while nothing to do:
    c.wait()
    # here we have something to do with the lock held
c.unlock()

So the refactoring is to move the unlock/wait/lock sequence
into the condition object. Using with, you could write this
as

with threading.Condition() as c:
  while nothing to do:
    c.wait()
    # do work

So no need for an additional context manager here.

Regards,
Martin




More information about the Python-Dev mailing list