I have been asked this question in an interview and I thought to take advice from you guys.
Say I have a pre-compiled library which references to some function say "strtok".
There is no source code for this library.
$ nm lib.a | grep strtok
U _strtok
Your target system uses a RTOS and you have multiple threads which make calls into the library.
Q) Why might this be a problem?
To my understanding, this shouldn't be a problem . I mean there is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes and race conditions
2 Answers 2
strtok
is not thread-safe because it saves its state in static memory between calls. If two threads make concurrent or interleaved calls to strtok, they will get erroneous results. The strtok_r
variant returns a pointer to the caller to use for future invocations on the same string. There are many other C and POSIX functions that are not safe to use from multiple threads.[1,2]
In modern software, with multithreading being commonplace, it is less likely that library implementers will build unsafe functions like this. However, you cannot assume that is the case by default.
- Thread-safety and POSIX.1
http://www.unix.org/whitepapers/reentrant.html - The GNU C Library: Nonreentrancy
http://www.gnu.org/software/libc/manual/html_node/Nonreentrancy.html
If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes and race conditions
I think you just hit what they were after. In any language you will have parts of it that are not thread safe and need synchronization mechanisms to prevent issues (look at the .net List for a specific example that I am familiar with). This is even more true with third party libraries.
Calling the same function from 2 threads is only problematic when synchronization is not considered and the library is not thread safe*.
*of course there may be specifics I am unaware of.
Explore related questions
See similar questions with these tags.