Is there a definitive list of functions that are thread-safe in Mac OS X's implementation of the C standard library?
There is a good answer here with regards to glibc
and f*()
functions specifically, but I have failed to find any such resource with respect to OS X. Is there such a thing?
For example, are strptime()
and strftime()
thread-safe? printf()
? These are some that may have internal buffers that I would not want to mess up. :)
The standard C printf() and scanf() functions use stdio so they are thread-safe. The standard C printf() function is susceptible to changes in the locale settings if called in a multithreaded program.
Almost certainly if you were to ask a more detailed question specifying what it is you want to do, the answer would be "no, it is not thread-safe". But only almost. If by "thread-safe" you mean something like the difference between Vector and ArrayList in Java, then C++ standard containers are non-thread-safe.
A side note: std::cout is thread-safe The C++11 standard guarantees, that you must not protect the single characters, written to std::cout. Each character will atomically be written.
A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface.
The Single Unix Specification gives a fairly short list of functions that are allowed to be non–thread-safe (except that functions in the "Legacy Feature Group" are allowed to be non–thread-safe despite not being listed there). The list includes strtok()
, which Dave mentions in his answer, but does not include strptime()
, nor strftime()
, nor printf()
.
This StackOverflow answer asserts, in response to a question that is fairly similar to this one, that OS X does support the above aspect of the spec, so I think that's probably the best list to use. (You'll probably also be interested in the rest of that question, and in the other answer to it, by the way.)
Any function which seems to have some magical remembering power, is likely not to be thread-safe. Any function which returns a pointer you aren't expected to free()
is very frequently not thread-safe.
Many of the functions you really have to worry about return char*
, or struct foo*
. Although this isn't a perfect rule, this is often indicative of a function which has some sort of static storage, and isn't thread-safe.
strtok()
is a simple example of is, and has been succeeded by strtok_r()
which is thread-safe. For many non-thread-safe functions, there exists a function_r()
(r for reentrant) which is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With