What is the difference between reentrant and thread-safe?
Short answer: A thread-safe function works correctly when called from several threads at the same time; it may achieve that with locks. A reentrant function works correctly when a call is interrupted and the same function is called again on the same execution context (ISR, signal handler, recursion) before the first call finishes. A function that uses a mutex is thread-safe but not reentrant: if an ISR interrupts it while it holds the lock and calls it again, the ISR waits forever for a lock that can only be released by the code it interrupted.
| Reentrant | Thread-safe | |
|---|---|---|
| Problem it solves | interruption and re-entry on the same core/thread | concurrent calls from different threads |
| Typical technique | no shared state; caller-provided buffers | locks around shared state, or no shared state |
| Mutex inside | breaks reentrancy (deadlock from an ISR or signal handler) | fine |
| Example | strtok_r, memcpy |
malloc in glibc (locks), printf (locks the stream) |
Examples
static uint32_t total;
static mutex_t m;
void add_threadsafe(uint32_t v) /* thread-safe, NOT reentrant */
{
mutex_lock(&m);
total += v;
mutex_unlock(&m);
}
uint32_t add_pure(uint32_t a, uint32_t b) { return a + b; } /* both */
Which functions are both: those with no shared mutable state (pure functions of their arguments), or that update shared state with a single atomic operation that also works from interrupts (e.g. atomic_fetch_add on a lock-free atomic).
Async-signal-safe is the POSIX term for functions that may be called from a signal handler: it is a strict form of reentrancy. write(), _exit() and sem_post() are; printf() and malloc() are not.
Practical rule for firmware: functions used from ISRs must be reentrant (no locks, no static buffers). Functions used only by tasks can use RTOS mutexes for thread safety.