[cse491] homework4 question
C. Titus Brown
ctb at msu.edu
Sat Sep 20 19:51:08 PDT 2008
On Sat, Sep 20, 2008 at 10:34:17PM -0400, Alex Nolley wrote:
-> I'm a little uncertain about some code I have in my homework 4 webserver.
-> Since our program has to catch any exceptions that occur in the threads, I
-> first make a thread t that contains the info to spawn a client connection.
-> Next, I spawn the thread in a try, except clause where the except will catch
-> any exception, print out it's information to standard output and then pass
-> and continue with a new thread. The code is similar to this:
->
-> while 1:
->
-> # Setup the connection stuff
->
-> t = threading.Thread(target=handle_connection, args(client_sock,))
->
-> try:
-> t.start()
-> except:
-> print "An exception happened:", sys.exc_info()[0]
->
-> Will this code allow for true mulit-threading or does the try, except clause
-> prevent that from happening?
Hey Alex,
good question! You could try experimenting, but the short answer is
that true multithreading *does* happen, because exceptions raised
inside threads don't propogate outside the thread. So the 'try/except'
in the above code only deals with the 't.start()' statement but not
anything in the 'handle_connection' function. Threads are entirely
independent of the main code execution task.
In brief, you need to put the try/except into handle_connection.
Note that 'traceback.print_exc()' will print the normal traceback
output.
cheers,
--titus
p.s. This also points out an exception to the try/finally rule:
try:
t.start()
finally:
# do something
Here, 'finally' is run immediately after t.start() in the originating
thread, and not in the thread 't'.
--titus
--
C. Titus Brown, ctb at msu.edu
More information about the cse491-fall-2008
mailing list