POSIX threads and signal interaction

This is just for your interest, it’s not SDL related.

I hope this was educational. :slight_smile: It sure was for me. :slight_smile:

Thank you, that corrected a few misconceptions I had regarding POSIX signals…

:slight_smile:

cya
Josh----
‘Cloning and the reprogramming of DNA is the first serious step in
becoming one with God.’
- Scientist G. Richard Seed

This is just for your interest, it’s not SDL related.

For POSIX, there are two kinds of signals, asynchronous, and synchronous.

Synchronous signals are those generated by code exceptions, like a segmentation
fault, or floating point violation. These signals are sent to the thread which
generates them.

Asynchronous signals are those arriving from external events, like a keyboard
break or an alarm signal. These are sent to the entire process, and are
actually received by only one thread which is chosen non-deterministically.

Signal handlers are set for the entire process, meaning that different threads
may not set their own signal handlers. HOWEVER, each thread may set a separate
signal mask, allowing or disallowing signals to be delivered to that thread.

In general, it is recommended by POSIX that instead of handling asynchronous
signals in random threads, you should create a separate thread that waits for
asynchronous signals (using the new sigwait() API) and then uses IPC to let
the other threads know that an asynchronous signal has arrived.

Under Linux, things are a little tricky, because at the moment, each thread
has it’s own process id. This means that another process can target a specific
thread with a signal, which isn’t allowed by the POSIX standard. Also, sending
a signal to a process group (e.g. Ctrl-C) signals all threads in the process,
also violating the POSIX standard.

This is no longer a problem under SDL. When a thread is first created, the
SDL library sets the signal mask for that thread so all asynchronous signals
will be ignored by that thread. This means that only the main thread will
receive asynchronous signals, and they will be handled in the main code,
as expected by the application. The only exception to this is SIGUSR1 and
SIGUSR2, which are used by the Linux implementation of pthreads.

I hope this was educational. :slight_smile: It sure was for me. :slight_smile:

See ya!
-Sam Lantinga (slouken at devolution.com)–
Author of Simple DirectMedia Layer -
http://www.devolution.com/~slouken/SDL/