CSE Roadmap

Core tier · about 4 hours · 7 parts

Part 4 of 7 · 3 min read

Thread-safe functions

In plain words: A function is thread-safe if several threads can call it at the same time and each gets the right result. Many standard C functions are not, because they keep their result or their position in a hidden static variable that all threads share.

Take strtok, which splits a string into pieces. It remembers where it stopped in a static variable. Even in one thread this breaks when one loop calls it inside another loop:

char text[] = "a:1,b:2,c:3";
for (char *p = strtok(text, ","); p; p = strtok(NULL, ",")) {
    char copy[16]; strcpy(copy, p);
    char *k = strtok(copy, ":");         /* the inner call overwrites the saved position */
    printf("[%s] ", k);
}

With strtok, the output was [a] [1]. The inner call changed the single saved position, so the outer call lost its place: its second piece was the stray 1 and the loop stopped before b and c. The replacement strtok_r takes a pointer to a variable that the caller owns, so every loop has its own position:

with strtok:   [a] [1]
with strtok_r: [a] [b] [c]

The suffix _r stands for reentrant: a reentrant function keeps no hidden shared state, so it can be called again while an earlier call is still in progress, from the same thread or another one.

Another example is localtime, which converts a time to a calendar date and returns a pointer to one shared buffer. A test starts two threads at a time, one converting the time 0 (the year 1970) and one converting a time in 2023, and reads the year twice. In a run of 2,000 rounds, the program printed buffer changed under us 1,938 times, mostly as 1970 became 2023: one thread's result was overwritten by the other's. The safe version is localtime_r, which writes into a buffer the caller provides.

Unsafe Safe replacement Why
strtok strtok_r The position is kept in the caller's variable
localtime, gmtime localtime_r, gmtime_r The caller gives the result buffer
rand rand_r The caller keeps the seed
asctime, ctime asctime_r, ctime_r The caller gives the buffer

The manual page of each function states whether it is thread-safe, in a section called ATTRIBUTES.

Thread-safe function

A thread-safe function is a function that gives correct results when several threads call it at the same time, because it keeps no unprotected shared state, or protects the state it keeps with a lock. A reentrant function is one that uses only its own arguments and local variables, so a call can safely begin before an earlier call has finished.

Example: strtok_r is reentrant because its position is stored in a variable the caller owns, while strtok is not because its position is a hidden static variable.

Check yourself: 1. Why does strtok break when one loop calls it inside another loop? 2. What does the suffix _r mean? 3. How does localtime_r avoid the problem of localtime?