A beginner's question on thread

Donn Cave donn at drizzle.com
Wed Apr 7 01:37:41 EDT 2004


Quoth Timothy Wu <huggiepython at graffiti.idv.tw>:
| I'm writing a small utility that listens for socket connections, and 
| also repond to user inputs via a text menu selection.
|
| In order to respond to both the user and the incoming connections I 
| figure I need to use thread.
|
| I think I would use the main thread to handle the menu and spawn a 
| thread which listens on a socket.
|
| Now my question is, how do I terminate the server thread if user wants 
| to exit the application? If the server just sit there and listen the 
| thread would never terminate by itself. What kind of inter-thread 
| communications are available and where would I find info/tutorial on that?

Well, that's the deal.  Use threads to solve a problem, and now
you have two problems.  

I'd probably do it the way Aurelio Martin proposed, with I/O to
the socket thread.  It's much neater than whacking the thread,
which is the alternative.

I wouldn't necessarily use threads in the first place, though.
I think it really depends on the user interface - usually that
has to be the dispatch core of the application, and if it's
built for threads, then there you go.  Typically there will be
some provision for dispatch on an I/O channel like a socket.
If you're writing your own user interface, probably just reading
and writing to the tty, and the socket thread is going to be
the one and lonely extra thread - then don't do it, I'd say.
Use select.select, or a package like asyncore or twisted or
whatever (not very familiar with that territory, I just use select.)

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list