Tkinter, Sleep and threads

Tim Peters tim.one at home.com
Thu Jul 5 00:25:59 EDT 2001


[Mike Clarkson]
> In _tkinter.c, in Tkapp_MainLoop():
>
>  If Python is compiled WITH_THREADs, then it uses  a 20 msec. Sleep
> loop to check signals and do Tcl events.
>
> The current problem is threefold:
> 1) An idle Tkinter application consumes about 5% of the CPU, because
> it is in a tight 20 msec Sleep loop. The equivalent Tk application
> uses 0%.

Did you measure this?  I measure idle Tkinter apps on Windows using from 0%
CPU when in the background, to about 0.20% when foreground and they need to
blink a cursor at me.  Yes, it may wake 50 times per second, but it consumes
only enough cycles for Tcl_DoOneEvent(TCL_DONT_WAIT) to report there's
nothing to do, and then goes straight to sleep again.  If you're measuring
5%, something sounds hosed on your box.

> 2) Say you establish a ^C signal hanler, then create and use a Tkinter
> dialog (that uses Tk's vwait, like ColorChooser). If you pop up the
> dialog, enter the mainloop, and hit ^C, the signal handler will not be
> called until you finish choosing a color. (I presume all other Python
> threads will also be forced to wait.)

The Tcl_DoOneEvent call is in the scope of

    Py_BEGIN_ALLOW_THREADS
    ...
    Py_END_ALLOW_THREADS

brackets, so other Python threads run independently of what Tk is doing.
How signal handlers work in the presence of threads varies widely across
platforms.

For the rest of this, you're going to have to get the attention of Fredrik
and Guido; making Tk work vaguely nicely *at all* in the presence of threads
was a multi-year effort (although I doubt it accounted for 5% of their
mental cycles the whole time <wink>).

> ...
> (BTW, what is the difference in Python-C-API between Tkapp_MainLoop
> returning NULL and returning Py_None?  I'm not a C programmer).

Throughout the C API, a NULL return means an error occurred, while a Py_None
return is "normal".






More information about the Python-list mailing list