Threads -- play well with others? If not, what instead?

Grant Edwards ge at nowhere.none
Mon Jun 12 15:30:11 EDT 2000


In article <8i34mr$9hti$1 at nntp6.u.washington.edu>, Russell E. Owen wrote:

>David Beazley's excellent "Python Essential Reference" says in the 
>section on threads: "In addition, many of Python's most popular 
>extensions such as Tkinter may not work properly in a threaded 
>environment."
>
>I assume it's true, but it was quite a bombshell. I was hoping to write 
>a networked GUI client, hence:
>- read data from a socket and fill in a GUI display
>- accept input from the user and write data to the socket
>I assumed I'd use two threads, one for input, one for output. Now I have 
>no idea what to do. Any suggestions?

In Tk, you can assign read handlers to file objects.  Anytime
there is data available to be read, the handler will be called.

Just open the socket connection and assign a read-handler to
it.  Piece-o-cake.  Here's an excerpt from a program that uses
that technique to handle data from a popen2'd child process:

------------------------------------------------------------

if cmd is None:
    exceptString = 'no executable specified'
    raise exceptString, cmd
                                        
self.__returnCode = -1
self.__child = popen2.Popen3(cmd)
self.__fd = self.__child.fromchild.fileno()

fcntl.fcntl(self.__fd, FCNTL.F_SETFD, FCNTL.O_NDELAY);


Tkinter.tkinter.createfilehandler(self.__child.fromchild,
                                  Tkinter.tkinter.READABLE,
                                  self.__stdoutHandler)
                                  
------------------------------------------------------------

self.__child.fromchild      is a file object connected to the "read" end of a pipe.
Tkinter.tkinter.READABLE    is a constant that tells Tk what you care about.
self.__stdoutHandler        is a function to call when the file object has data available.

-- 
Grant Edwards                   grante             Yow!  I want to kill
                                  at               everyone here with a cute
                               visi.com            colorful Hydrogen Bomb!!



More information about the Python-list mailing list