[Python-Dev] release candidate rules and timeit API question

Guido van Rossum guido@python.org
Tue, 01 Jul 2003 07:12:11 -0400


>     Tim> It's not so fine that this delicate code is duplicated, so I'd
>     Tim> rather see an internal refactoring to use a common backoff-polling
>     Tim> class.
> 
> I recently copied it to my own code as well.  I'd like to see it whacked
> into something reusable.  This seems to work:
> 
>     import time
>     class Timeout(Exception): pass
> 
>     def await_condition(predicate, timeout):
>         delay = 0.0005
>         endtime = time.time() + timeout
>         while True:
>             if predicate():
>                 return
>             remaining = endtime - time.time()
>             if remaining <= 0:          # time's up, predicate always failed
>                 raise Timeout
>             delay = min(delay * 2, remaining, .05)
>             time.sleep(delay)           # reduce CPU usage by using a sleep
> 
> Skip

I wonder if the right refactoring wouldn't be to add an acquire with
timeout method to the built-in lock type?

--Guido van Rossum (home page: http://www.python.org/~guido/)