Tkinter and asyncronous socket

Steve Holden steve at holdenweb.com
Wed Nov 26 07:42:31 EST 2008


maxlosblob at gmail.com wrote:
> Hi all, I'm new to python and I've been spending the last week on GUI
> that refresh its content based on data periodically coming from a
> remote socket.
> I succeded in doing it (thanks newsgroups and online manual!) using
> the Tkinter.after method to implement a busy wait on the socket (which
> I had previously set to non blocking)
> I should be happy with it, but on windows (application must be multi-
> platform) the busy wait leads to a 100% CPU usage. I'm trying to
> implement it the other way round: a "socket process" that updates a
> label (or a queue object) in the GUI. I can't figure out how to do
> this. Anyone can post hints? With some details, maybe?
> 
Processes are probably a bit heavyweight for this purpose: they create
difficulties in communication (unless you use the new multiprocessing
library in 2.6).

One approach would be to run the socket code in blocking mode in a
separate thread started by the (main program) GUI thread at program
startup, and communicating results back via a Queue.Queue or similar to
the GUI thread. That thread wakes itself up once every (say) 500 mS to
check for updates from the socket side.

You should see your CPU utilization go down then. The threading.thread
library is actually much easier to use than you would think, though it's
possible to get things wrong by assuming data sharing will work in ways
it actually doesn't. But if you have the main thread pass a Queue to the
networking thread, that should be a reliable means of communication.

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list