Creating & joining threads
Start worker threads, pass them arguments and collect their results.
By Invicly Tech, , in Linux System Programming. About 12 minutes to read.
In short
Threads are multiple flows of execution inside one process, sharing its memory, descriptors and signal handlers, each with its own stack and registers. pthread_create starts a thread running a function, and pthread_join waits for it and collects its result. Shared memory makes threads fast to communicate but easy to get wrong.
Explained simply
A thread is one line of work inside a program. A normal program has one thread: it starts in main and does one thing at a time. With more threads, the same program can do several things at once, for example compress four files on four CPU cores.
All threads in a process live in the same memory. They see the same global variables, the same heap and the same open files. Each thread only has its own stack (for local variables) and its own CPU registers. This sharing makes threads fast to talk to each other, and also easy to break.
You start a thread with pthread_create and give it a function to run plus one pointer argument. Later you call pthread_join, which waits until that thread finishes and hands you the pointer it returned. Think of it as: start a helper, go on with your work, then wait for the helper's answer.
Every thread you start must be either joined or detached. Joined means someone waits for it. Detached means it cleans up after itself when it ends. Forget both, and each finished thread leaks some memory, a bit like a zombie process.
Press Play on a diagram to walk through it one step at a time.
- Share the address space and fds
- Cheap to create and switch
- Communicate through shared memory
- One crash kills the whole process
- Separate address spaces
- Stronger isolation
- Communicate through IPC
- A crash affects only one process
- 1Shared: code and globals
Every thread runs the same program text
- 2Shared: heap
malloc memory is visible to all threads
- 3Shared: fds, cwd, signal handlers
close() in one thread closes it for all
- 4Private: stack per thread
Locals and call frames, 8 MiB default
- 5Private: registers, TID, errno
Also signal mask and thread-local data
In depth
What a thread really is on Linux
Linux has no separate thread object inside the kernel. A thread is a task, the same kind of object as a process, created with clone (or clone3) and flags that say: share the memory, the open files, the signal handlers and the process ID. glibc's thread library (NPTL) maps every pthread to exactly one kernel task, so the kernel scheduler sees and runs each thread on its own.
All threads share one PID, which getpid returns. Each also has its own thread ID, returned by gettid. You can see them with ps -T -p PID, with top -H, or as folders under /proc/PID/task. Thread creation is fast (microseconds, not milliseconds) because nothing is copied, but it is not free. For many short jobs, reuse a fixed pool of threads instead of creating one per job.
- ps -T -p PID lists threads with their TIDs (the SPID column)
- ls /proc/PID/task shows one folder per thread
- pthread_setname_np gives a thread a name (max 15 chars) shown by top -H
Passing arguments and getting results
pthread_create takes exactly one void pointer as the argument. To pass several values, put them in a struct and pass its address. That struct must stay alive until the thread has read it, so do not point at a loop variable or at a local that goes out of scope. An array of structs, one per thread, is the simplest safe pattern.
The thread returns a void pointer, which pthread_join gives back to you. Never return the address of a local variable: the thread's stack is gone once it exits. Either return a pointer to heap memory (the joiner frees it), or write the result into the argument struct and return NULL. For a small integer, you can cast it through intptr_t, which is common in examples but less clear than a struct.
- One struct per thread, kept alive until join
- Return heap memory or write into the argument struct
- pthread_exit(ptr) ends the thread early with a result
Join, detach, and how a program ends
pthread_join blocks until the target thread ends, then frees its leftover resources. You may join a thread only once, and only if it is joinable. pthread_detach (or creating the thread with the PTHREAD_CREATE_DETACHED attribute) says nobody will join; the system frees the thread when it ends. Use detach for fire-and-forget work, but remember that you then have no easy way to know when it finished.
How the program ends matters too. Returning from main calls exit, which ends every thread at once, even ones in the middle of a write. If main should end but workers should keep going, call pthread_exit(NULL) in main instead. Most programs simply join every worker before returning.
- 1pthread_create
Kernel task created, function starts
- 2Runs its function
Uses its own stack, shares the heap
- 3Returns or pthread_exit
Result pointer is kept
- 4Waits to be joined
Stack and descriptor not yet freed
- 5pthread_join
Caller gets the result, resources freed
Errors, -pthread and attributes
pthread functions do not set errno. They return 0 on success or an error number such as EAGAIN (too many threads or no memory). Print it with strerror(rc), not perror. Always check pthread_create: on a busy box it does fail.
Build with gcc -pthread for both compiling and linking. It sets the right macros and links the thread library. Since glibc 2.34 the thread functions live inside libc itself, but -pthread is still the portable, correct flag.
Attributes (pthread_attr_t) change how a thread starts. The most useful one is the stack size. Each thread gets a stack of RLIMIT_STACK size by default, usually 8 MiB of virtual memory. That memory is only reserved, not used, but if you start thousands of threads, pthread_attr_setstacksize with something like 256 KiB keeps the address space small.
- gcc -Wall -pthread prog.c -o prog
- rc = pthread_create(...); if (rc) fprintf(stderr, "%s\n", strerror(rc));
- ulimit -s shows the default stack size in KiB
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Create threads with pthread_create~40m
- 2Pass arguments and return values~40m
- 3Join or detach threads~40m
- 4Compare threads with processes~40m
- 5Build with -pthread~40m
Key points
- Compile and link with -pthread.
- Pass arguments through a void pointer, and give each thread its own argument struct.
- Every thread must be joined or detached so its resources are freed.
- pthread functions return an error number instead of setting errno.
Key terms
Tap a card to flip it. 0/6 known
Examples
#include <pthread.h>
#include <stdio.h>
struct job { int id; long result; };
static void *work(void *arg) {
struct job *j = arg;
for (long i = 1; i <= 1000000; i++) j->result += i % (j->id + 2);
return NULL;
}
int main(void) {
pthread_t t[4]; struct job jobs[4];
for (int i = 0; i < 4; i++) { jobs[i] = (struct job){ i, 0 }; pthread_create(&t[i], NULL, work, &jobs[i]); }
for (int i = 0; i < 4; i++) { pthread_join(t[i], NULL); printf("job %d: %ld\n", i, jobs[i].result); }
return 0;
}Four workers, each with its own argument struct. Build with gcc -pthread.
Return a result from a thread the safe way
We want a worker to compute a value and hand it back. Step 1: pass the input through the void pointer. Step 2: the thread allocates the result on the heap, because its own stack disappears when it returns. Step 3: main checks the return code of pthread_create and prints the error with strerror, since pthread functions do not set errno. Step 4: pthread_join stores the thread's return value in res, and main frees it.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void *square(void *arg) {
long n = *(long *)arg, *out = malloc(sizeof *out); /* heap outlives the thread */
if (out) *out = n * n;
return out; }
int main(void) {
long n = 7; pthread_t t; void *res;
int rc = pthread_create(&t, NULL, square, &n);
if (rc) { fprintf(stderr, "pthread_create: %s\n", strerror(rc)); return 1; }
pthread_join(t, &res);
if (res) { printf("%ld\n", *(long *)res); free(res); }
return 0; }Look at a running program's threads
A server feels slow and you want to know which thread is busy. Step 1: list the threads of the process; each line has its own TID in the SPID column. Step 2: top -H shows CPU use per thread, and names set with pthread_setname_np appear there. Step 3: each thread is also a folder under /proc/PID/task, where you can read its status and what it is waiting on. Step 4: gdb can attach and print a backtrace of every thread.
PID=$(pidof myserver)
ps -T -p "$PID" # one line per thread
top -H -p "$PID" # live CPU use per thread
ls /proc/"$PID"/task # one folder per TID
grep Threads /proc/"$PID"/status # thread count
sudo gdb -p "$PID" -batch -ex "thread apply all bt"Quick reference
- Compile and link with gcc -pthread; never forget it on the link line
- pthread_create(&t, NULL, fn, arg) returns 0 or an error number, never -1
- pthread_join(t, &ret) waits and frees; join each joinable thread exactly once
- pthread_detach(pthread_self()) makes a thread clean up after itself
- Return heap memory or fill the argument struct; never return a pointer to a local
- Returning from main ends all threads; pthread_exit(NULL) in main does not
- pthread_attr_setstacksize shrinks the default 8 MiB stack for many threads
- ps -T -p PID and top -H show threads; gettid() gives the kernel thread ID
Common mistakes
- Passing &i from a loop so every thread sees the same changing variable.
- Returning a pointer to a thread's local variable from the thread function.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Start 5 threads that each print "hello from thread N" with the correct N (0 to 4), then join them all.
- Exercise 2medium
Sum an array of 10 million longs with 4 threads. Each thread sums its own slice into its argument struct, and main adds the 4 partial sums.
- Exercise 3hard
Start 2000 threads that each sleep for one second, first with default attributes and then with a 64 KiB stack. Compare VmSize in /proc/self/status while they run.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use -pthread or -lpthread?
- Use -pthread on both the compile and the link command. It links the library and also sets compiler macros for thread-safe code, which -lpthread alone does not.
- How many threads can a Linux process have?
- Thousands are fine. Limits come from /proc/sys/kernel/threads-max, the per-user process limit (ulimit -u counts threads), and address space for stacks. More threads than CPU cores rarely helps CPU-bound work.
- Are threads faster than processes?
- Creating and switching threads is cheaper, and sharing data needs no copying. But processes are safer: one crash does not take down the others. Web servers like nginx use processes, many databases use threads, and both work well.
- Is printf thread-safe?
- Yes, glibc stdio functions lock the stream, so lines from different threads will not mix inside one call. Output from separate calls can still interleave in any order.