Start here
clone-style primitives. C++/Rust/JVM threads ultimately call into the same OS services, learn pthread concepts once, then map to your language.Thread libraries (what they hide)
pthreads expose create/join, mutexes, condition variables, barriers, and attributes (stack size, detach state). The implementation wires TLS, robust mutex paths, and integration with debuggers (TSAN).
By the end of this page you should be able to
- Name three pthread objects and what problem each solves.
- Explain why checking every `pthread_*` return matters in C.
- Relate NPTL to 1:1 threading on Linux.
Operating systems · Threads
Thread libraries
pthread, Windows threads, language runtimes
TL;DR
Thread libraries wrap `clone`/CreateThread with portable APIs: mutex/cond/rwlock, TLS, cancellation, and stack management. They cooperate with the kernel for scheduling signals and set robust mutex priorities for priority inheritance edge cases.
Summary
Libraries are where textbook pthread APIs meet production: you configure stack, detach/join behavior, scheduling class (where permitted), and signal masks, misconfiguration causes latent production bugs.
Deeper narrative
NPTL on Linux integrates with clone, TLS, robust mutexes, and `set_tid_address` for clear child TID reporting. Libraries also implement thread pools, work queues, and affinity helpers atop raw pthreads.
Mechanism (step by step)
pthread API
Create/join, mutex/cond, rwlock, barriers, POSIX standard surface.
Runtime integration
C++ `std::thread`, Rust std, JVM all lower to pthreads or OS primitives.
Thread-local state
Compiler + libc cooperate for `__thread`/TLS descriptors.
Debugging hooks
`TSAN`, `gdb thread apply all bt`, `libpthread` lock elision paths.
Key insights
Cancellation is hard
Stack size limits
Priority inheritance mutexes
Runtime integration
Did you know?
Common pitfalls
Mixing C++ threads with pthread locks
Must match memory ordering and destructor ordering, deadlocks lurk.
Ignoring errno pthread APIs
Return codes vs exceptions, check every `pthread_*` return.
Glossary
NPTL
Robust mutex
TSAN
Interview follow-ups
- What does `PTHREAD_MUTEX_ERRORCHECK` buy you?
- How does glibc implement robust mutexes across process death?
- Why might `pthread_attr_setstacksize` matter on 32-bit?
Callouts
Debugging
`gdb thread apply all bt` is invaluable when deadlocks span many pthreads.
Walkthrough & deep dive
Left: practical “how would I use this?” threads. Right: slower, code-leaning explanations, open one panel at a time so the page does not feel like a wall of sameness.
Walkthrough
API quiz
Deep dive
Robust mutexes
If a holder dies, robust mutexes can return EOWNERDEAD, allows recovery paths in shared memory IPC.
pthread hello
#include <pthread.h>
void* run(void* arg) { return NULL; }
int main(){ pthread_t t; pthread_create(&t,NULL,run,NULL); pthread_join(t,NULL); }Self-check
1Linux pthread mutexes often use…
2TLS provides…
3Join vs detach