Concurrency and threads
On this page
A thread is a single execution sequence that can be scheduled on its own. This article covers the thread abstraction, the pthread API, how threads are implemented and switched, and how Linux creates them.
Why concurrency
Operating systems and applications have to handle many things at once: process execution, interrupts, background tasks, system maintenance. Humans are not good at keeping track of many simultaneous things, and threads bridge that gap. Typical uses:
- Servers: handle multiple connections at once.
- Parallel programs: better performance.
- User interfaces: stay responsive while computing.
- Network- and disk-bound programs: hide latency.
A word processor might have one thread each for reading the keyboard, formatting, saving to disk, spell-checking and drawing the GUI.
Definition and abstraction
A thread is a single execution sequence that represents a separately schedulable task. It's single-sequence, so it uses the familiar programming model; and it's separately schedulable, so the OS can run or suspend it at any time.
The thread abstraction: there is an infinite number of processors, and threads execute with variable speed. Each thread runs on its own virtual processor with unpredictable speed, so programs must be designed to work with any schedule.
“Each thread runs on its own virtual processor with unpredictable and variable speed” was the answer in both 2023 (Q13) and 2025 (Q9). The main benefit of threads over processes is that they need less resources and overhead to create (2024 Q11).
Thread operations
thread_create(thread, func, args)- Create a new thread to run
func(args). thread_yield()- Give up the processor voluntarily, so another thread can be scheduled.
thread_join(thread)- In the parent, wait for the thread to exit, then return.
thread_exit- Quit the thread and clean up, waking up the joiner if any.
In POSIX these are pthread_create, pthread_join, pthread_exit and pthread_self. Compile with -lpthread (or -pthread).
threadHello
#include <stdio.h>
#include <pthread.h>
#define NTHREADS 10
pthread_t threads[NTHREADS];
void *go (void *n) {
printf("Hello from thread %ld\n", (long)n);
pthread_exit(100 + n);
// REACHED?
}
int main() {
long i;
for (i = 0; i < NTHREADS; i++)
pthread_create(&threads[i], NULL, go, (void*)i);
for (i = 0; i < NTHREADS; i++) {
long exitValue;
pthread_join(threads[i], (void*)&exitValue);
printf("Thread %ld returned with %ld\n", i, exitValue);
}
printf("Main thread done.\n");
return 0;
}
- The “Hello” lines can come in any order: the scheduler decides.
- The “Thread i returned” lines always come in order, because
mainjoins thread 0, then 1, and so on. - The line after
pthread_exitis never reached. - When thread 5 prints, at most 11 threads exist (main and all ten) and at least 2 (main, which is still waiting to join, and thread 5).
Since pthread_create only passes one void * argument, pass a pointer to a struct when the thread needs more (the threaded server exercise passes the socket fd and address this way). If you had to wrap pthread_create in a function taking a single parameter, that parameter would be the function the thread should run.
Fork/join concurrency
Threads can create children and wait for them. If data is only shared before the fork and after the join, the threads are independent. Examples: a web server with a thread per connection (as long as connections are independent), merge sort, parallel memory copy.
Implementation
Each thread has a thread control block (TCB) with its saved registers and a pointer to its own stack. Shared state (code, globals, heap) is in the process. A thread moves between the states init → ready → running → waiting → ready … → finished.
Creating a thread
- Allocate a thread control block.
- Allocate a stack.
- Build a stack frame for the base of the stack (a stub), and put
funcandargson it. - Put the thread on the ready list. It runs some time later, maybe right away.
The stub calls (*func)(args) and calls thread_exit() if the function returns. The new stack is set up as if the thread had saved its state in switchframe, so the first switch “returns” into the stub.
Context switches
Voluntary: thread_yield, or thread_join when the child hasn't finished. Save registers on the old stack, switch to the new stack and thread, restore registers from the new stack, return. This works the same for kernel threads and user threads.
Involuntary: an interrupt or exception, or a higher-priority thread becoming ready. The timer or I/O interrupt tells the OS another thread should run; the end of the interrupt handler calls switch, so processor state is saved twice (once by the handler, once by the switch).
Threads that only switch by yielding are called cooperative; threads that can be interrupted at any time are pre-emptive.
Kernel and user-level threads
- Kernel threads
- Only available inside the kernel. To the kernel, a kernel thread and a single-threaded user process look much the same.
- Multithreaded processes using kernel threads (Linux, macOS)
- User thread = kernel thread. Thread operations are system calls, and the kernel does the context switch. Simple, but many transitions between user and kernel mode.
- User-level threads (“green threads”, early Java)
- A library inside a single-threaded process does the context switch, with preemption via an upcall (signal) on a timer interrupt. Use multiple processes for parallelism.
Thread stacks
Each thread has a fixed-size stack. If a thread recurses too deeply, it overflows its stack: the exercises suggest trying it to see what happens.
Threads in Linux
Each pthread_create becomes a clone (or clone3) system call. clone takes flags saying what to share: address space, file descriptors, signal handlers and so on. fork is essentially clone with no sharing flags, so the child gets its own copy of everything.
strace -e trace=clone,clone3,write ./threadHello 2>&1 | grep -E "clone|Hello"
That's why, in forkVsThread.c, a forked child's shared++ does not change the parent's variable, while two threads incrementing shared both change the same variable. Without synchronisation, two threads each doing shared++ ten thousand times will not reliably reach 20000; see synchronisation.
Speedup from parallelism
The parallel.c exercise counts to N twice, first serially, then in two threads. time reports three numbers:
- real
- Wall-clock time from start to finish.
- user
- CPU time in user mode, summed over all cores.
- sys
- CPU time in kernel mode (creating, scheduling and joining threads).
With two cores, real time roughly halves while user time stays about the same: the same total work spread over two cores. It is slightly more than half because of thread creation and scheduling overhead, and adding threads stops helping once there are more threads than cores.
On earlier exams
- 2023, question 11 – Sum with a thread
- 2023, question 13 – Thread abstraction
- 2023, question 14 – Wrapping pthread_create
- 2024, question 11 – Threads versus processes
- 2024, question 12 – Yielding
- 2024, question 23 – Threading: fill in the blanks
- 2025, question 7 – Yielding
- 2025, question 9 – Thread abstraction
- 2025, question 16 – Cooperative thread
Practise this topic in the quiz (15 questions)