Linux System Programming · intermediate · ~10 min
Recognize what makes a function thread-safe, and what does not.
A thread-safe function can be called from several threads at the same time and still produce the documented result.
In multithreaded code, concurrently means two or more threads may run the same function at overlapping moments. A thread-safe function behaves correctly even then.
Functions fall into three rough groups.
A reentrant function uses only its arguments and local variables. It shares no state at all.
strlen(const char *s).These functions do have shared state, but they take a lock internally to protect it. The caller does not need to do anything extra.
malloc on glibc.These functions use static state (data that persists between calls and is shared by all callers). The caller must serialize access to them.
strtok, gmtime, asctime, rand._r variant you can use instead: strtok_r, gmtime_r, rand_r.When you write your own functions, follow these rules.
_Atomic./* Not thread-safe — internal static buffer */
char *to_hex(unsigned x) {
static char buf[16];
snprintf(buf, sizeof buf, "%x", x);
return buf; /* every caller shares this buffer */
}
/* Thread-safe — caller provides the buffer */
char *to_hex_r(unsigned x, char *buf, size_t cap) {
snprintf(buf, cap, "%x", x);
return buf;
}
strtok, gmtime, asctime, or ctime in multithreaded code. Use the _r variants instead.int." A read-modify-write (such as count++) is never atomic on a plain int. Use _Atomic to make it safe.strtok, gmtime, asctime, and rand; use their _r variants._Atomic.