Let's summarize the preceding points in the form of a table that tells us how to achieve the all-important goal of thread-safety for all our functions:
Approach to make a function thread-safe | Comments |
Use only local variables | Naive; hard to achieve in practice. |
Use global and/or static variables and protect critical sections with mutex locks | Viable but can significantly impact performance [1] |
Refactor the function, making it reentrant-safe-eliminate the use of static variables in a function by using more parameters as required | Useful approach—several old foo glibc functions refactored to foo_r. |
Thread local storage (TLS) | Ensures thread safety by having one copy of the variable ... |