Re: Exceptions and thread-safety
On 2007-10-30 15:20, Ioannis Gyftos wrote:
I am developing a little utility for my desktop, and at some point I
have a 'worker' thread and a (main) GUI thread. Depending on
circumstances, on some rare cases I wanted to display a window, but
since i use the QT library, the window must be created from the main
thread. So I need the 'worker' thread to interrupt its work, notify
the main thread, the main thread to display it, and then restart the
whole process after user interaction.
The way I implemented this, is that I throw an exception which is
caught at the run() function of the worker thread, and then it
notifies the GUI thread (through the signal/slot mechanism which is
offtopic). So far this has worked nicely on my machine.
(Though I am not sure if this the best approach since it's for
personal use, but for academic reasons, if you have a better idea I am
more than happy to hear it :P).
The only thing that might change is the throwing of the exception. I am
not sure if you do it because further execution is not possible, or to
return to the run() function. If it is the latter you can skip the
throwing and just signal the slot from where you are.
My question is, supposing I have multiple 'worker' threads and an
exception occurs, is this thread safe? I googled a bit, and found that
some compilers have thread-safety on exceptions, but some don't. What
does the standard say? I would like to maintain a little portability
on the major desktop OS, so even if only the major desktop compilers
support this it is acceptable.
If I understand you correctly the exception is caught in the same thread
as it was thrown (I assume that the run() function is where the new
thread starts execution). So far you should be thread-safe (but since
the standard says nothing on the subject some wacky implementation is
possible). The problem is with the signal/slot mechanism which might be
thread-safe or not, a quick look in the Qt docs tells me that it should
be safe in Qt4 and onwards (see the docs about the QObject::connect()
method, especially the last argument), for Qt3 you need to do some research.
--
Erik Wikstr??m