Sub topic 8
Threads and What They Share
Assume you know basic C, pointers, processes, virtual memory, and process states. This chapter uses POSIX threads, commonly called pthreads.
What a Thread Is
A thread is an independent path of execution inside a process. A process can contain one thread or several threads. Each thread can run instructions, be scheduled by the operating system, and block while waiting for input or another event.
Threads in one process share the process's resources:
- The code, global variables, and heap are shared.
- Open files and other process-level resources are shared.
- Each thread has its own program counter, CPU registers, and stack.
- Each thread has its own execution state.
The stack is private because function calls and local variables must not overwrite another thread's call frames. The heap is shared, so two threads can access the same dynamically allocated object.
| Resource | Shared by threads? | Reason |
|---|---|---|
| Global variables | Yes | They are part of the process address space |
| Heap memory | Yes | Threads use the same virtual address space |
| Stack | No | Each thread needs private call frames |
| CPU registers | No | Each thread has separate execution state |
| Open file descriptors | Usually yes | They belong to the process |
| Program counter | No | Each thread may execute a different instruction |
Process and Thread Comparison
Creating a thread is usually cheaper than creating a process. A new process normally receives a separate address space. A new thread reuses its process's address space. Threads therefore make communication through shared memory simple, but they also make accidental interference possible.
A data race occurs when multiple threads access the same memory concurrently, at least one access is a write, and the program has no proper synchronization. The result can depend on timing. A mutex, or mutual-exclusion lock, allows only one thread at a time to enter a protected section.
A Small pthread Example
The worker thread changes a global variable. The main thread calls pthread_join, which waits for the worker to finish before reading the result.
#include <pthread.h>
#include <stdio.h>
static int shared = 0;
void *worker(void *arg) {
(void)arg;
shared = 42;
return NULL;
}
int main(void) {
pthread_t thread;
pthread_create(&thread, NULL, worker, NULL);
pthread_join(thread, NULL);
printf("shared = %d\n", shared);
return 0;
}Compile it on a POSIX system with cc example.c -pthread -o example. A forked child would initially receive a separate copy of shared; a thread writes the same shared object.
Exercise
A process has three threads. Which execution information must be saved separately for each thread: the heap, the program counter, or the CPU registers?
Show answer
The program counter and CPU registers must be saved separately. The threads share the process heap.