[Tkinter-discuss] Proposal for thread-safe Tkinter

Guilherme Polo ggpolo at gmail.com
Mon Oct 27 18:10:33 CET 2008


On Mon, Oct 27, 2008 at 12:59 PM, Allen Taylor
<Allen.Taylor at mdacorporation.com> wrote:
> All,
> After a very helpful discussion with "Guilherme Polo <ggpolo at gmail.com>", we
> have come to the following conclusion regarding multithreaded applications
> and Tkinter. Although Tk is technically thread-safe (if built with
> --enable-threads), practically speaking it still has problems when used in
> multithreaded applications.

Now that I reread it, I see you said "Tk is technically thread-safe
(if built with --enable-threads)". It is not true, what happens is
that tkinter makes it thread safe by using some mutexes and scheduling
actions to go through the thread that created the tcl interpreter,
which otherwise would happen elsewhere. But tk isn't thread safe per
se  (only tcl, since version 8.1).  At the same time, if tk is
compiled without thread support but python has thread support, then
tkinter fails miserably to protect against multiple threads from
python from accessing tk.

And again, your module does help in this case since all the
interaction to tk will occur through main thread, independent of tk
having thread support or not.

> The problem stems from the fact that _tkinter
> attempts to gain control of the main thread via a polling technique. If it
> succeeds, all is well. If it fails, however, the application receives an
> exception with the message "RuntimeError: main thread is not in main loop".
> There is no way to tell when this might happen, so calling Tk routines from
> multiple threads seems to be problematic at best.
> The mtTkinter module I published last week
> (http://tkinter.unpythonic.net/wiki/mtTkinter) solves this problem by
> marshaling calls coming from multiple threads through a queue which is read
> by an 'after' event running periodically in the main loop. This is similar
> to the technique used in many other platforms (e.g., .NET's
> InvokeRequired/Invoke mechanism). The technique used in mtTkinter is
> exception-safe as well, marshaling exceptions through a response queue back
> to the caller's thread.
> If a similar technique were employed in _tkinter instead of the polling
> technique, that would be a preferable solution. In the meantime, mtTkinter
> will work as a good stop-gap measure.
> Allen B. Taylor



-- 
-- Guilherme H. Polo Goncalves


More information about the Tkinter-discuss mailing list