Are functions in the C standard library thread safe? Are functions in the C standard library thread safe? c c

Are functions in the C standard library thread safe?


You can find that list here, at chapter 2.9.1 Thread-Safety : http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_09_01

That is, this is a list over functions that posix does not require to be thread safe. All other functions are required to be thread safe. Posix includes the standard C library and the typical "unix" interfaces. (Full list here, http://pubs.opengroup.org/onlinepubs/9699919799/functions/contents.html)

memcpy() is specified by posix, but not part of the list in 2.9.1, and can therefore be considered thread safe.

The various environments on linux at least tries to implement posix to the best of its abilities - The functions on linux/glibc might be thread-safe even if posix doesn't require it to be - though this is rarely documented. For other functions/libraries than what posix covers, you are left with what their authors have documented...

From what I can tell, posix equates thread safety with reentrancy, and guarantees there is no internal data races. You, however, are responsible for the possible external data races - such as protecting yourself from calling e.g. memcpy() with memory that might be updated concurrently.


It depends on the function, and how you use it.

Take for example memcpy, it is generally thread safe, if you copy data where both source and destination is private to a single thread. If you write to data that can be read from/written to by another thread, it's no longer thread safe and you have to protect the access.


If a glibc function is not thread-safe then the man page will say so, and there will (most likely) be a thread safe variant also documented.

See, for example, man strtok:

SYNOPSIS #include

   char *strtok(char *str, const char *delim);   char *strtok_r(char *str, const char *delim, char **saveptr);

The _r (for "reentrant") is the thread-safe variant.

Unfortunately, the man pages do not make a habit of stating that a function is thread safe, but only mention thread-safety when it is an issue.

As with all functions, if you give it a pointer to a shared resource then it will become thread-unsafe. It is up to you to handle locking.