Condition.wait() behavior with timeout

Ross Boylan ross at biostat.ucsf.edu
Mon Jan 30 15:14:33 EST 2012


The Python 2.7 documents for the threading module says, in part,
wait([timeout])¶
        
        Wait until notified or until a timeout occurs. If the calling
        thread has not acquired the lock when this method is called, a
        RuntimeError is raised.
        
        This method releases the underlying lock, and then blocks until
        it is awakened by a notify() or notifyAll() call for the same
        condition variable in another thread, or until the optional
        timeout occurs. Once awakened or timed out, it re-acquires the
        lock and returns.
        
First, the documentation does not say what the return value is.  I was
hoping it was True or False depending on whether a timeout occurred, as
Event.wait().

Second, the "Once awakened or timed out, it re-acquires the lock and
returns" sounds very strange.  If there was a timeout then an attempt to
acquire the lock will block until it is released.  Since there was no
notify there almost certainly will be no release() immediately after the
tiemout.  Which would make the timeout pretty useless (since the thread
that called wait() blocks even after the timeout expires), and might
cause a race on the condition object.

I've googled around, but haven't found anything quite on topic.
http://bugs.python.org/issue1175933 from 2005 requested adding a timeout
to Condition.wait(), a proposal rejected in 2009.  Clearly it's there
now.

http://www.gossamer-threads.com/lists/python/dev/761847 complains there
is no return value from wait and so no way to determine if a timeout
occurred.   One response was
<quote>
>GR> How am I supposed to know if it was notified or if it timed out? 

Normally you wouldn't have to know. The logic of your program should be 
such that you wait until a certain condition is satisfied. After each 
wait you usually check that condition anyway, like: 
</quote>
http://bugs.python.org/issue1175933#msg48141 also refers to the need to
check things after returning from wait().  But both of these cases seem
to refer to a scenario in which there are many workers waiting on the
condition, not one with notify() and a single thread waiting (which is
what I'm thinking about).  The thread does say there is no return value;
it seems to me it would be useful to document that if it's still true
(or True :).

Can anyone help me understand what's going on?

Thanks.
Ross Boylan




More information about the Python-list mailing list