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 ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.