Summary table – approaches to making functions thread-safe

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 per thread; toolchain and OS-version-dependent. Very powerful and easy to use.
Thread-specific data (TSD) Same goal: make data thread-safe older implementation, more work to use.
Table 1: Approaches to making functions thread-safe

[1] Though we say that using the mutex can significantly impact performance, the mutex performance is, in the normal case, really very high (largely due to its internal implementation on Linux via the futex–fast user mutex).

Let's check out these approaches in more detail.

The first one, using only local variables, being a fairly naive approach, will probably only work well with small programs; we shall leave it at that.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset