[Python-Dev] Any objections to adding threading.Timer?

Tim Peters tim.one@home.com
Sat, 11 Aug 2001 13:29:40 -0400


[Aahz]
> Unfortunately, I don't think this is possible unless we add some
> platform-specific code to thread.c, and you'll need to ask Uncle Timmy
> for that.  To the extent that I'm an expert on threading, I'm only an
> expert on Python threads.

AFAIK there are no reliable x-platform timeout facilities.  Even on Windows,
the current scheme sucks in (at least) three ways:

1. time.time() updates only 18.2 times per second on Windows, so
   55ms is the finest granularity possible via any time.time()-based
   approach.

2. time.sleep() on Windows truncates the argument to an integer
   number of milliseconds (due to limitations of the Win32 Sleep),
   so any delay value < 0.001 acts like Sleep(0), i.e. returns
   immediately if no other threads are waiting (that's how Win32
   Sleep(0) works).

3. As Glyph so visibly discovered on c.l.py recently, time.time() can
   "go backwards", and especially on laptops with Intel SpeedStep
   CPUs.

All that said, I'd still change the timeout loop from

                endtime = _time() + timeout
                delay = 0.000001 # 1 usec
                while 1:
                    gotit = waiter.acquire(0)
                    if gotit or _time() >= endtime:
                        break
                    _sleep(delay)
                    if delay < 1.0:
                        delay = delay * 2.0

to

                endtime = _time() + timeout
                delay = 0.001 # 1 ms
                while 1:
                    gotit = waiter.acquire(0)
                    if gotit:
                        break
                    remaining = endtime - _time()
                    if remaining < 0:
                        break
                    delay = min(delay * 2, remaining, .05)
                    _sleep(delay)