Technical skill

Linux P-threads

Let one program do more than one thing

A program may need to keep responding while it handles a second task. A thread is one path of work inside a running program, and a program can start several threads. They share the process memory, including global variables and the heap (memory used for data created while the program runs), and open files. Each thread has its own stack, the memory used for its function calls, and its current execution state. Shared data must be coordinated, or two threads may change it at the same time and produce an unexpected result.

On Unix-like systems, POSIX (Portable Operating System Interface) is a standard that describes common programming interfaces. The Pthreads library is the C interface for creating and coordinating threads in one process. A thread's start routine has the form void *function(void *argument). A void * is a generic pointer to data; here the argument points to the string the worker reads. The program uses pthread_create to start the thread. New threads are joinable by default, and pthread_join waits until a joinable thread has finished. The argument object must remain valid while the new thread uses it.

A worker thread in C

This program starts a worker, passes it a string literal, and waits for it to finish:

#include <pthread.h>
#include <stdio.h>

static void *report(void *arg)
{
    const char *label = arg;
    printf("worker: %s\n", label);
    return NULL;
}

int main(void)
{
    pthread_t thread;
    int error = pthread_create(&thread, NULL, report, "health-check");
    if (error != 0) {
        fprintf(stderr, "pthread_create failed: %d\n", error);
        return 1;
    }

    error = pthread_join(thread, NULL);
    if (error != 0) {
        fprintf(stderr, "pthread_join failed: %d\n", error);
        return 1;
    }
    return 0;
}

The pthread_t value is a handle for referring to the new thread, not its process ID. The string literal stays available for the program's lifetime, so the worker can safely read it. The second argument to pthread_join is NULL, so this example discards the worker's return value. On Linux, compile with cc -pthread worker.c -o worker, then run ./worker. Here cc is the C compiler and -pthread enables the thread support needed when compiling and linking. Pthread functions return an error number directly; unlike many system calls, they do not report it through errno, the error variable used by many C library calls. Check the returned number.

Keep shared data safe

If two threads update the same variable at once, the final value can depend on which update happens first. That is a data race. A mutex is a lock: a thread locks it before entering a critical section, the small part of code that uses shared data, then unlocks it when done. Every access that needs protection must use the same mutex; a lock cannot protect code that ignores it. Keep the protected work small, and acquire several mutexes in a consistent order so two threads do not wait on each other forever.

Release a mutex before waiting on slow network or disk activity when the design permits it. A thread that holds a lock while blocked can stop other threads from making progress. Only one thread should join a given target; simultaneous joins have undefined results, and cyclic joins can deadlock.

Modern glibc on Linux uses NPTL, which maps each POSIX thread to a kernel-schedulable thread. Inspect a running program's threads with ps -L or under /proc/PID/task. These views can reveal blocked or CPU-heavy threads, but a list does not show what each thread is doing.

Interactive exercises

Materials

Skillsets
Skillset Devops preview
image descriptionDevops
by Ajay Kumar
2004 users
Skillset Linux administrator preview
image descriptionLinux administrator
by Infinite Education
3080 users
Skillset Devops preview
image descriptionDevops
by Dio
3 users
Do you know that ...?
Any useful or interesting facts about the skill. Any peace of information would be useful