Linux System Programming · intermediate · ~10 min
Recognise what makes a function thread-safe and what doesn't.
A thread-safe function can be called from multiple threads concurrently and still produce the documented result. Three rough categories:
strlen(const char *s). Automatically thread-safe.malloc on glibc.strtok, gmtime, asctime, rand. Each has a reentrant _r variant: strtok_r, gmtime_r, rand_r.When you write your own helpers:
_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;
}
int." Read-modify-write is never atomic on an int without _Atomic.Thread-safe = no unprotected shared state. Avoid strtok/gmtime/asctime/rand; use *_r variants. Prefer pure functions.