[Return to Bookshelf] [Contents] [Previous Section] [Next Section] [Index] [Help]


3.2.3 Unsafe

When you must call code that is not thread-safe, you need to ensure serialization and exclusivity of the unsafe routine across all threads in the program. Using a mutex lock when calling any unsafe code accomplishes this. All threads and libraries using the routine should use the same mutex. Note that even if two libraries carefully lock a mutex around every call to a given routine, if each library uses a different mutex, the routine is not protected against multiple simultaneous calls from different libraries.

Furthermore, you must be aware that in many cases you need to protect more than just the call itself. You need to use or copy any static return values before releasing the mutex, and you may need to protect a sequence of calls rather than just a single call.

If a routine is not specifically documented as thread-reentrant or thread-safe, you should assume that it is unsafe. You should never assume that a routine is fully thread-reentrant unless that is specifically documented; many times, routines can rely on static data in ways that are not completely obvious from the interface. A routine carefully written to be thread-reentrant but that calls some other routine that is unsafe without proper protection, is actually unsafe itself.