Sub topic 8
Threads and What They Share
This chapter assumes you know what a process is, how the PCB stores process state, and how fork creates a child with its own address space. Basic C and pointers are also assumed. By the end you should be able to say which resources a thread shares with its process and which it owns, and to predict program output where fork and threads are mixed.
Why threads exist
A process bundles two things: a unit of resource ownership (address space, open files) and a unit of execution (program counter, registers, stack). A thread separates them. A process can have several threads, and each thread is one independent flow of execution inside that process.
Creating a process with fork is expensive. The kernel must duplicate the page tables and the PCB, and the two processes can only communicate through IPC. Threads in one process already see the same memory, so they cooperate by reading and writing shared variables.
Typical uses:
- A web server handles each request in its own thread.
- A GUI keeps the interface responsive while another thread does a long computation.
- A numerical program splits an array across threads to use several cores.
What threads share and what they own
All threads of a process share the resources of the process. Each thread has its own execution context.
| Shared by all threads of a process | Private to each thread |
|---|---|
| Code (text) segment | Thread ID |
| Global and static data | Program counter |
| Heap | Register set |
| Open files and file descriptors | Stack |
| Signal handlers | Thread state (running, ready, blocked) |
| Process ID, user ID, working directory | Thread-specific data, `errno` copy |
Each thread needs its own stack because it has its own chain of function calls, local variables, and return addresses. Each thread needs its own registers and program counter because it is at a different point in the code.
In the kernel, a thread is usually described by a small thread control block (TCB) that holds the private items. The PCB holds the shared items once.
A thread sees shared memory
The following program creates one thread. The thread writes to a global variable, and after pthread_join the main thread sees the new value.
#include <stdio.h>
#include <pthread.h>
static int shared = 0;
static void *worker(void *arg) {
int local = *(int *)arg;
shared = local;
return NULL;
}
int main(void) {
pthread_t tid;
int value = 42;
pthread_create(&tid, NULL, worker, &value);
pthread_join(tid, NULL);
printf("shared = %d\n", shared);
return 0;
}The output is shared = 42. Compile with gcc file.c -pthread. If you replaced pthread_create with fork, the child would change only its own copy of shared, and the parent would still print 0.
Note that local lives on the worker's own stack, while value lives on the main thread's stack. The worker can still read value through the pointer, because stacks are in the shared address space. They are private by convention, not protected by hardware. This is a common source of bugs: passing the address of a local variable to a thread that outlives the function.
Processes versus threads
| Aspect | Process | Thread |
|---|---|---|
| Address space | Own | Shared with other threads of the process |
| Creation cost | High | Low |
| Context switch cost | High (page tables, often TLB flush) | Lower within the same process |
| Communication | IPC (pipes, shared memory, messages) | Shared variables |
| Isolation | A crash does not directly affect others | A bad pointer or crash can kill the whole process |
| Blocking | Blocks only itself | With kernel threads, one thread blocking does not block the others |
A thread switch inside one process does not change the address space, so the kernel does not switch page tables. This is the main reason it is cheaper than a process switch.
What happens to threads on fork, exec, and exit
These interactions are favorite GATE material.
forkin a multithreaded program. On POSIX, the child contains only a copy of the thread that calledfork. The other threads do not exist in the child.exec. The whole process image is replaced, and all threads other than the caller vanish.exitor returning frommain. The entire process ends, including every thread. To let other threads finish, the main thread must callpthread_exitorpthread_jointhem.pthread_exitin a thread. Only that thread terminates.
Fork counting is unchanged for threads. For example, this program prints hello 8 times, because each fork doubles the number of processes (2^3 = 8):
#include <stdio.h>
#include <unistd.h>
int main(void) {
fork();
fork();
fork();
printf("hello\n");
return 0;
}A common GATE twist is a fork call inside a thread function. Each fork still produces one extra process, but that process holds only the single forking thread.
Races on shared data
Sharing makes threads convenient and also dangerous. Consider two threads each executing counter++ on a shared global 1000 times. The statement compiles to three steps: load, add, store. If a context switch happens between load and store, one update is lost, and the final value can be below 2000. This is a race condition. The fix is mutual exclusion (a mutex or atomic operation), which later chapters on synchronization cover. For now, remember that shared memory means shared responsibility.
Benefits and costs
Benefits:
- Responsiveness: one thread can block on I/O while others continue.
- Resource sharing: no IPC setup is needed.
- Economy: creation and switching cost less than for processes.
- Scalability: threads of one process can run on different cores at the same time.
Costs:
- Races and deadlocks must be handled by the programmer.
- No memory isolation between threads.
- Debugging is harder because behaviour depends on timing.
Common errors
- Saying threads share the stack. They do not; each has its own stack and registers.
- Saying
forkcopies all threads. It copies only the calling thread. - Forgetting
pthread_join, somainreturns and kills the other threads before they finish. - Assuming a thread's
returnends the process. Only returning frommain(or callingexit) does. - Passing a pointer to a loop variable into several threads, so they all read the changing value.
Exercise
A process has 4 threads. One thread calls fork() once. How many threads exist in total afterwards, and which of them does the child contain?
Show answer
The parent process still has 4 threads. The child is a new process containing exactly 1 thread, a copy of the thread that called fork. In total there are 5 threads across the two processes. The other 3 threads are not copied into the child.
Exercise
Name which of these are shared by threads of one process: heap, stack, program counter, open file descriptors, global variables, register set.
Show answer
Shared: heap, open file descriptors, global variables. Private to each thread: stack, program counter, register set.
Exercise
Why is a context switch between two threads of the same process usually cheaper than one between two different processes?
Show answer
Both threads use the same address space, so the kernel does not need to switch page tables or flush the TLB. It only saves and restores the thread's registers, program counter and stack pointer.