Home : C++ : Thread-safe Signal Handling

Thread-Safe Signal Handling

I was working on a system that used a thread-safe queue and needed to add a message to the queue in response to a signal. In my case, it had to handle alarm signals after a specific timeout but the techniques discussed in this section apply to all kinds of signals.

The problem was that, as signals are handled on a process wide basis, if the signal fired whilst the queue was locked, no other threads could continue (and unlock the queue) until the signal handler had finished. This discussion continues to refer to the thread-safe queue but technique applies equally to any shared resource.

The Responder Thread

To get around the deadlock, I used a separate thread (called the "Responder Thread") that would block against a condition fired from a generic signal handler. This thread would then call the user supplied signal handler on an equal footing with the rest of the system.

In the program I was writing, signals weren't fired very often, therefore I used a single responder thread to handle all types of signal, but this design could be extended to use a responder thread for every different type of signal that is to be handled.

The CSignalManager Class

I designed a class to encapsulate this functionality. The class constructor would be used to start the responder thread - and its destructor to stop it. A method was provided to register signal handlers much like the signal() function in POSIX.

The class was a singleton since it should not be possible to handle the same signal in two different ways.

Comments

Members have left 0 comments about this page:
Please Login or Register to comment on this page.

Resources
Tools
User
Last Updated Wednesday, 24-May-2006 22:39:17 BST