What are the guidelines to write thread-safe UNIX code in C and C++?
I know only a few:
- Don't use globals
- Don't use static local storage
What others are there?
What are the guidelines to write thread-safe UNIX code in C and C++?
I know only a few:
What others are there?
It really comes down to shared state, globals and static local are examples of shared state. If you don't share state, you won't have a problem. Other examples of shared state include multiple threads writing to a file or socket.
Any shared resource will need to be managed properly - that might mean making something mutex protected, opening another file, or intelligently serializing requests.
If two threads are reading and writing from the same struct, you'll need to handle that case.
Beware of the sem_t
functions, they may return uncompleted on interrupts, IO, SIGCHLD etc. If you need them, be sure to allways capture that case.
pthread_mut_t
and pthread_cond_t
functions are safe with respect to EINTR
.
The simple thing to do is read a little. The following list contains some stuff to look at and research.
static
variables, and any shared dynamically allocated memory.pthread_cond_init
and related functions.Once you understand the basics, learn about the common problems so that you can identify them when they occur:
A good open book about concurrency in general can be found here: Little Book of Semaphores
It presents various problems that are solved step-by step and include solutions to common concurrency issues like starvation, race conditions etc. It is not language-specific but contains short chapters about implementing the solutions in C with the Pthread-Library or Python.