Thread safety via TLS
The preceding discussion was with regard to the already existing standard C library, glibc, and its API set. What about MT applications that are newly designed and developed? Obviously, the code we write for them must be thread-safe.
Let's not forget how we rendered our testit_mt_refactored function to become thread-safe by refactoring it – adding an iobuf parameter that passed along the address of the buffer to use for I/O—guaranteeing the buffer will be unique for each thread and thus thread-safe (without any need for locking).
Could we get such functionality automatically? Well, yes: the compiler (GCC and clang) does provide an almost magical feature to do something similar: TLS. With TLS, a variable marked with ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access