glibc Breakdown thread pthread
This document provides a detailed breakdown of the internal __pthread_create_2_1
function from glibc, which is responsible for thread creation in POSIX-compliant systems.
__pthread_create_2_1
is the internal name for the pthread_create
function. you can find the entire source code in glibc/nptl/pthread_create.c or in here
Each major segment of the function is listed below with a short explanation and a link to a more detailed page in the same folder.
π§΅ Overview
Function signature:
int __pthread_create_2_1(pthread_t *newthread, const pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg);
This function creates and starts a new thread with the specified attributes and entry point.
π¦1. Deferred Initialization
-
What it does: Ensures one-time initialization in case the library starts in a single-threaded state.
-
Why it matters: Prepares glibc internals for multithreading.
βοΈ 2. Thread Attribute Handling
-
What it does: Uses user-provided thread attributes or retrieves system defaults.
-
Why it matters: Ensures that every thread has a valid and complete set of attributes.
π 3. Stack and Thread Descriptor Allocation
-
What it does: Allocates memory for the thread stack and sets up the internal thread descriptor (
struct pthread
). -
Why it matters: This is where the actual memory for the thread is reserved.
π§ 4. TCB and Thread Descriptor Initialization
-
What it does: Initializes fields in the thread descriptor such as start routine, argument, flags, guards, etc.
-
Why it matters: Prepares everything needed before launching the thread.
π 5. Scheduling Parameter Determination
-
What it does: Chooses whether to use the parent threadβs scheduling policy or the explicitly defined one.
-
Why it matters: Impacts how the OS schedules the new thread.
π 6. Thread Count Management and Signal Blocking
-
What it does: Increments thread count and blocks signals to avoid race conditions during creation.
-
Why it matters: Ensures the new thread starts in a controlled, race-free environment.
π€ 7. Thread Creation and Debug Event Reporting
-
What it does: Calls the actual system-level thread creation and notifies any attached debugger.
-
Why it matters: Itβs where the thread actually starts running.
β»οΈ 8. Post-Creation Signal Restoration and Error Handling
-
What it does: Restores signal mask and handles any failures that occurred during creation.
-
Why it matters: Prevents resource leaks and ensures consistent thread state.
πͺ 9. Finalization and Cleanup
-
What it does: Unlocks and frees resources, sets internal flags, and returns to the caller.
-
Why it matters: Completes the thread creation process cleanly.