Chapter 31: Thread Safety & Per-Thread Storage
POSIX Threads — Making Functions Safe in Multithreaded Programs
From The Linux Programming Interface — EmbeddedPathashala Tutorial Series
4
Core Topics
5
HTML Files
10+
Code Examples
20+
Interview Q&A
What This Chapter Covers
When multiple threads run the same function at the same time, things can go wrong — shared variables get corrupted, buffers get overwritten, and data races cause unpredictable bugs. This chapter explains thread safety: what it means, why it matters, and how to achieve it. You will learn about reentrancy, one-time initialization using pthread_once(), per-thread storage using the Thread-Specific Data (TSD) API, and the simpler __thread keyword for Thread-Local Storage (TLS). These are essential skills for any Linux systems programmer working with multithreaded code.
Key Concepts in This Chapter
Thread Safety Reentrancy Critical Section Mutex pthread_once() PTHREAD_ONCE_INIT Thread-Specific Data pthread_key_create() pthread_setspecific() pthread_getspecific() Destructor Function Thread-Local Storage __thread strerror_r() Non-reentrant Functions
Tutorial Files
Understand what thread safety means, why functions fail when called from multiple threads, the difference between serialization and critical-section approaches, and what reentrancy is. Covers the SUSv3 list of non-thread-safe functions and why they exist.
Thread Safety Definition Global/Static Variables Problem Mutex Serialization Critical Sections Reentrancy Non-thread-safe Functions List _r Reentrant Variants
Library functions often need to initialize shared resources exactly once, no matter how many threads call them. Learn how
pthread_once() solves this problem elegantly, and when to use it.pthread_once() API PTHREAD_ONCE_INIT pthread_once_t Library Initialization Pattern Why Static Mutex Works Too
Thread-Specific Data (TSD) lets each thread have its own private copy of a variable, without changing the function’s interface. Learn the full TSD API: key creation, set/get, destructors, and internal implementation details.
TSD Concept pthread_key_create() pthread_setspecific() pthread_getspecific() Destructor Functions Internal Implementation Key Limits
Walk through a complete, real-world example: making
strerror() thread-safe using TSD. Covers the non-thread-safe original, the broken behavior it produces, and the full TSD-based fix with all steps explained.Non-safe strerror() Implementation Demonstrating the Bug Thread-Safe strerror() with TSD Step-by-Step TSD Flow Verifying Thread Safety
Thread-Local Storage (TLS) is a simpler alternative to TSD. Learn how the
__thread specifier works, its rules and limitations, and how it compares to TSD. Includes a TLS-based strerror() rewrite.__thread Keyword TLS vs TSD Comparison Declaration Rules Kernel/Compiler Support strerror() with TLS
Start Learning
Begin with File 1 and work through each topic in order for the best understanding.
