6 ms·
> surely it doesn't touch any global (or per-thread) state Not necessarily. An implementation might choose to e.g. use some kind of cache similar to what the J
by lmm 2y ago
> surely it doesn't touch any global (or per-thread) state
Not necessarily. An implementation might choose to e.g. use some kind of cache similar to what the JVM does with interned strings, and then a function like strcmp() might behave badly if it happened to run while that cache was halfway through being rebuilt.
- SomeoneFromCA 2y agoContrived example, never seen in reality.
- jcul 2y agoYou could be surprised. For example, recently I wanted to call `gettid()` in a signal handler. Which I guessed was just a simple wrapper around the syscall. However, it seems this can cache the thread ID in thread local storage (can't remember exact details). I switched to making a syscall instead.
- SomeoneFromCA 2y agoWell, this is possible for sure, but not for primitive functions, such as strcmp. It just does not happen in practice.
- jcul 2y agoFor functions like strcmp, I think they must be signal safe, to be POSIX compliant. https://man7.org/linux/man-pages/man7/signal-safety.7.html https://man7.org/linux/man-pages/man7/signal-safety.7.html If it's on this list I generally trust it is safe. I guess my point is, that if it's not, even a simple function may appear safe, but could do surprising things.
- lmm 2y agoThe JVM does it in reality, I can't see why a C runtime wouldn't.
- SomeoneFromCA 2y agoIt in theory may, but no one does.
- lilyball 2y agoA function like strcmp() cannot assume that if it sees the same pointer multiple times that this pointer contains the same data, so there's no opportunity for doing any sort of caching of results. The JVM has a lot more flexibility here in that it's working with objects, not raw pointers to arbitrary memory.
- lmm 2y ago> A function like strcmp() cannot assume that if it sees the same pointer multiple times that this pointer contains the same data For arbitrary pointers no. But it could special-case e.g. string constants in the source code and/or pointers returned by some intern function (which is also how the JVM does it - for arbitrary strings, even though they're objects, it's always possible that the object has been GCed and another string allocated at the same location).