IDLE replacement?

Tim Peters tim.one at home.com
Tue Jun 5 19:44:04 EDT 2001


[Adonis]
> ...
> IDLE seems to crash on me everytime i attempt to create a thread and the
> debug dumps all the code of IDLE at the same time locking the program
> up.
>
> is it my code? or a bug in IDLE?

It's more a problem with Tcl/Tk, and you'll find the same kind of problems
trying to mix threads with many other GUI systems.

You *can* mix threads with IDLE, but it requires great care:  you have to
make sure that "the main thread" is the only one that ever calls into Tk, or
gets called back from Tk.  Tk gets lost if any other thread talks to it.
So, for example, you have to arrange for all stdout printing to be done only
by the main thread (since Tk is actually in charge of drawing the pixels in
the IDLE shell window, which is where stdout gets redirected).  For example,
this output:

Thread 0 says 0.
Thread 1 says 0.
Thread 2 says 0.
Thread 0 says 1.
Thread 2 says 1.
Thread 1 says 1.
Thread 1 says 2.
Thread 0 says 2.
Thread 2 says 2.
Thread 1 says 3.
Thread 0 says 3.
Thread 2 says 3.
Thread 1 says 4.
Thread 0 says 4.
Thread 1 says 5.
Thread 2 says 4.
Thread 1 says 6.
Thread 1 says 7.
Thread 2 says 5.
Thread 0 says 5.
Thread 2 says 6.
Thread 0 says 6.
Thread 1 says 8.
Thread 1 says 9.
Thread 2 says 7.
Thread 0 says 7.
Thread 2 says 8.
Thread 2 says 9.
Thread 0 says 8.
Thread 2 says Finished.
Thread 1 says Finished.
Thread 0 says 9.
Thread 0 says Finished.
Done.

came from this program run under IDLE:

from threading import Thread
import Queue, time, random

q = Queue.Queue()
FINISHED_TOKEN = "Finished"

class test(Thread):
    def __init__(self, id):
        Thread.__init__(self)
        self.id = id

    def run(self):
        for i in range(10):
            q.put((self.id, i))
            time.sleep(random.random())
        q.put((self.id, FINISHED_TOKEN))

N = 3
threads = []
for i in range(N):
    t = test(i)
    threads.append(t)
    t.start()

count = 0
while count < N:
    tid, msg = q.get()
    print "Thread %d says %s." % (tid, msg)
    if msg == FINISHED_TOKEN:
        count += 1
        threads[tid].join()

print "Done."

Note the use of a Queue object to let threads queue up printing requests for
the main thread to deal with.





More information about the Python-list mailing list