Shared process resources và per-thread execution state

Threads chia sẻ address space/files nhưng mỗi thread có stack, registers, scheduling state, signal mask và thread-local storage.

Thread Model

POSIX/Linux mapping

NPTL maps pthreads 1:1 to Linux tasks; threads trong group share VM, files, signal handlers and more via clone flags. getpid returns TGID while gettid identifies task; tools may show both.

Thread lifecycle

pthread_create allocates stack/TLS and starts routine; join collects termination, detached thread releases automatically. Joinable thread never joined leaks user-space resources. Cancellation is cooperative with cleanup points/handlers and easy to misuse.

Stacks

Each thread reserves virtual stack with guard; actual resident grows on demand. Default stack × many threads consumes virtual/native memory and can hit address/cgroup/PID limits. Too small risks stack overflow from recursion/large frames/native calls.

Thread-local storage

TLS gives per-thread variables/keys but values/resources require cleanup. Thread pools make logical request outlive/reuse same OS thread, so ThreadLocal context can leak across requests and retain classloaders/data.

Signals

Each thread has mask; process-directed signal delivered to an eligible thread, thread-directed via pthread_kill/tgkill. Synchronous faults target causing thread. Signal handlers run asynchronously and may call only async-signal-safe functions.

Failure modes

Race/use-after-free, deadlock/livelock/starvation, leaked/detached threads, unbounded creation, stack exhaustion, TLS contamination and blocking all workers. Bound concurrency by downstream capacity and expose thread/queue lifecycle metrics.

pthreads(7) · pthread_create(3) · pthread_join(3) · nptl(7)
← MemoryScheduler →