473,836 Members | 1,596 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

threading.Event usage causing intermitent exception

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 watchForConditi on()
# do a bunch of stuff checking the system
myEvent.set()

cancelThread = threading.Threa d(target = watchForCancel)
cancelThread.se tDaemon(True) # so I can exit the program when I want
to
cancelThread.st art()
conditionThread = threading.Threa d(target = watchForConditi on)
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

Aug 8 '06 #1
2 2075
[ak*********@gma il.com]
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.
That's typical when the interpreter has torn so much of itself down
that there's not enough left in the `sys` module even to print
exception info gracefully. The easiest way to stop that is to stop
/trying/ to run Python code while the interpreter is tearing itself
down.
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()
Presumably this is some kind of poll-and-sleep loop? If so, add a
check to get out of the loop if myEvent.isSet() . Or if not, make it
some kind of poll-and-sleep loop ;-)
def watchForConditi on()
# do a bunch of stuff checking the system
myEvent.set()
Ditto.
cancelThread = threading.Threa d(target = watchForCancel)
cancelThread.se tDaemon(True) # so I can exit the program when I want to
And get rid of that. The comment doesn't make sense to me, and
forcing a thread to be a daemon is exactly what /allows/ the thread to
keep running while the interpreter is tearing itself down. That's why
"daemonism" isn't the default: it's at best delicate. I don't see a
real reason for wanting this here.
cancelThread.st art()
conditionThread = threading.Threa d(target = watchForConditi on)
conditionThread .setDaemon(True )
Ditto.
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.
At this point it's likely that even sys.stdout and sys.stderr no
longer exist. The "Unhandled exception" message is printed directly
to the C-level `stderr` instead.
...
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?
Stop forcing them to be daemon threads. The interpreter won't start
to tear itself down then before both threads terminate on their own.
To arrange for that, it's not necessary for the threads to become
aware of each other, but it is necessary for the threads to become
aware of another (shared) reason /for/ exiting. The most natural way
to do that, given what you said above, is to make both threads aware
that their shared myEvent event may get set "externally ", and to stop
when they find it has been set.
Aug 8 '06 #2

Tim Peters wrote:
[ak*********@gma il.com]
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.

That's typical when the interpreter has torn so much of itself down
that there's not enough left in the `sys` module even to print
exception info gracefully. The easiest way to stop that is to stop
/trying/ to run Python code while the interpreter is tearing itself
down.
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()

Presumably this is some kind of poll-and-sleep loop? If so, add a
check to get out of the loop if myEvent.isSet() . Or if not, make it
some kind of poll-and-sleep loop ;-)
after setting up the terminal correctly, ie changing buffering settings
etc. (I want to cancel with a single key-press with no "return" hit.
This was suprisingly difficult to do. The wait code is simply:

while keyPressed != 'q':
keyPressed = sys.stdin.read( 1)

The really annoying thing here, is that I cannot put in any other steps
in the while loop without sometimes missing the key press. I have to
unbuffer the terminal(otherw ise the read doesn't return until the enter
key is pressed), and for whatever reason performing any action no
matter how trivial leads to missing the key stroke on occasion - that's
why I pursued the daemon route.
>
def watchForConditi on()
# do a bunch of stuff checking the system
myEvent.set()

Ditto.
cancelThread = threading.Threa d(target = watchForCancel)
cancelThread.se tDaemon(True) # so I can exit the program when I want to
The conditional thread will never terminate without making the threads
aware of eachother. Setting them daemon allows the interpreter to
shutdown with one of them running - and ocaisonally cuases the error.
What I find interesting, the behavior only happens when I cancel, not
when the condition is reached.
And get rid of that. The comment doesn't make sense to me, and
forcing a thread to be a daemon is exactly what /allows/ the thread to
keep running while the interpreter is tearing itself down. That's why
"daemonism" isn't the default: it's at best delicate. I don't see a
real reason for wanting this here.
cancelThread.st art()
conditionThread = threading.Threa d(target = watchForConditi on)
conditionThread .setDaemon(True )

Ditto.
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.

At this point it's likely that even sys.stdout and sys.stderr no
longer exist. The "Unhandled exception" message is printed directly
to the C-level `stderr` instead.
exactly - giving me no way to swallow it.
...
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?

Stop forcing them to be daemon threads. The interpreter won't start
to tear itself down then before both threads terminate on their own.
To arrange for that, it's not necessary for the threads to become
aware of each other, but it is necessary for the threads to become
aware of another (shared) reason /for/ exiting. The most natural way
to do that, given what you said above, is to make both threads aware
that their shared myEvent event may get set "externally ", and to stop
when they find it has been set.
Due to the oddities of capturing that keypress at the console, I
suspect I can un-daemonize the conditional thread and check for
cancelled=True and have it return. Since the error only occurs when
the conditional thread is still running, undaemonizing it will prevent
that and allow the interpreter to shut down more gracefully.

Thanks for the advice.

Aug 9 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

77
5396
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for the moment. I'd be *very* grateful if people with any interest in multi-threading would read it (even just bits of it - it's somewhat long to go through the whole thing!) to check for accuracy, effectiveness of examples, etc. Feel free to mail...
8
346
by: Michael Culley | last post by:
I have some code that returns an event on a different thread. This is causing all sorts of problems, so I would like to just call a method on the main thread of the app and eliminate the second thread. The very first thing I want to do anyway is show a modal window so I don't need a second thread. Being that I know very little about threads can anyone gimme a solutions. Thanks, Michael Culley
2
1725
by: Nicholas | last post by:
I have this class that provides a disk-based queue for storing various items. As items are queued the event delegate is called and the consumer dequeues the object and processes it. This seems to work off and on. Sometimes the queue does not pick up a queued item until another item is queued. Can anyone see a problem with this class? *** Here's the interface and EventArgs... *** /// <summary>
11
3089
by: Tyler Sample | last post by:
I've been having strange thread conflicts, and after moving the relevant mutex higher and higher I've finally determined that the mutex doesn't seem to be working at all. Here is the relevant code: private static Mutex previewMutex = new Mutex(); private static void preview (string source, string target) {
0
1993
by: Colmeister | last post by:
I recently read Jason Clark's excellent article on Unhandled Exceptions (http://msdn.microsoft.com/msdnmag/issues/04/06/NET/default.aspx) and have attempted to incorporate the features he talks about in a new application I'm writing. However, when I try to use ThreadStart to do some work in a separate thread from my GUI, the methods Jason described don't seem to catch the exception. Take the following source code: Public Class...
12
5280
by: Perecli Manole | last post by:
I am having some strange thread synchronization problems that require me to better understand the intricacies of Monitor.Wait/Pulse. I have 3 threads. Thread 1 does a Monitor.Wait in a SyncLock block protecting a resource. Thread 2 and 3 also have a SyncLock block protecting the same resource and after executing some code in their blocks they both do a Monitor.Pulse to hand of the locked resource back to thread 1. While thread 1 has...
5
1374
by: venkat | last post by:
Hi, I have a page that calls a sql procedure and it runs for 20 - 40 min. I use usual threading for this page. <code>Thread objthread = new Thread(new ThreadStart(ticketingThread)); objthread.Start();</code> As i dont know when it will end. i never abort the thread. what happens is when user uses the page for 1 week, the page starts hanging. I dont know what happens. When i tried debugging it works fine.
0
1599
by: kingcrowbar.list | last post by:
Hello Everyone I have been playing a little with pyGTK and threading to come up with simple alert dialog which plays a sound in the background. The need for threading came when in the first version i made, the gui would freeze after clicking the close button until pygame finished playing the sound. In Windows it was acceptable because it could be ignored easily, but in
5
3520
by: JasonX | last post by:
Im having problems with my program, in that if I close the main form while my new thread is doing work which involves writing to the main form, then I get an error about a disposed object. To fix this, i have added an event, with the aim the main form subscribes to the event when it is created and unsubscribes as soon as its closed. This approach however has not fixed the problem. When the event is raised, it writes to the form using a...
0
10860
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10560
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10261
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6984
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5659
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5831
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4466
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4026
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3116
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.