threading.Event usage causing intermitent exception

akameswaran at gmail.com akameswaran at gmail.com
Tue Aug 8 17:23:55 EDT 2006


Admittedly this problem causes no actual functional issues aside from
an occasional error message when the program exits.  The error is:

Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:

Yes all that info is blank.  The application is a console application
that is waiting for some condition on the machine to happen.  However,
I leave open the possiblitiy to cancel by a single key press at which
point the program terminates.  Suffice it to say, I cannot perform both
checks without invoking threads as the key press gets "missed"
sometimes.  Below is a simplification of the code

canceled = False
myEvent = threading.Event()

def watchForCancel()
    global canceled
    # turn of terminal buffering and capture key presses here
    canceled = True
    myEvent.set()


def watchForCondition()
    # do a bunch of stuff checking the system
    myEvent.set()

cancelThread = threading.Thread(target = watchForCancel)
cancelThread.setDaemon(True)  # so I can exit the program when I want
to
cancelThread.start()
conditionThread = threading.Thread(target = watchForCondition)
conditionThread.setDaemon(True)
conditionThread.start()

myEvent.wait()

if cancelled:
    sys.exit(2)

# do more stuff if the condition returned instead of cancel and then
I'm done


I've left out most of the active code, just cuz I think it muddies the
water.  Now about 9 out of 10 times this works just fine.  However,
every once in a while I get the exceptions mentioned above, but only
when I cancel out of the operation.  I think the conditionThread is in
the process of shutting down and gets hosed up somehow and spits out an
exception, but the interpreter no longer has access to the info since
it is shutting down.  I know that the condition is not being met in
these situations, since the condition is based on a network client
sending a certain set of data, and in my tests I know that no client
has sent said data.     I haven't worried about this too much, as it
doesn't cause any functional problems, but it really irritates me.  I
suppose I could make the threads aware of each other, but that just
seems stupid.  Any suggestions on how to eliminate this intermittent
error?

Thanks




More information about the Python-list mailing list