Main Page | See live article | Alphabetical index

Thread-safe

Thread-safety is a programming concept applicable to multi-threaded programs. A piece of code is thread-safe if it is reentrant or protected from multiple simultaneous execution by some form of mutual exclusion.

Thread-safety is a key challenge in multi-threaded programming. It was once only a concern of the operating system programmer, but has of late become a commonplace issue to be tackled by the everyday programmer. In a multi-threaded program, several threadss execute similtaneously in a shared address space. Every thread has access to virtually all the memory of every other thread. Thus the flow of control and the sequence of accesses to data often have little relation to what would be reasonably expected by looking at the text of the program. This violates the principle of least surprise. Thread-safety is a property aimed for so as to minimize surprising behaviour, by re-establishing some of the correspondences between the actual flow of control and the text of the program.

The requirement for thread-safety highlights the inherent tension in multi-threaded programming: the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.

It is not easy to determine if a piece of code is thread-safe or not. However, there are several indicators that suggest the need for careful examination to see if it is unsafe:

A subroutine/"function" that only uses variables from the stack, depends only on the arguments passed in, and calls other subroutines with similar properties (a so-called "pure function" in C compiler circles) is reentrant, and thus thread-safe.

As seen in the definition, there are a few ways to achieve thread-safety:

A commonly used idiom combines both approaches:

The concept of exception safety is closely related, since it again deals with (synchronous) flows of control not directly correlated to the text of a program. Several of the idioms used are similar.