Operating Systems Module 2: Processes and threads Lesson 2.4 12 min

Threads

Threads let one process do several things at once. They share code, globals, heap and files, and each has its own stack and registers.

A web browser has to download a page, draw it, run its scripts and respond to your clicks, all at once. It could start a new process for each job, but then every job would need its own address space and a way to pass data around. Is there something lighter?

There is: a thread. A thread is a path of execution inside a process. A process always has at least one thread, and it can have many. The threads of one process share almost everything. That makes them cheap to create and easy to cooperate with, and it is also where the danger comes from.

What is shared and what is not

All the threads of a process live in the same address space. So they share:

  • the code (text),
  • the global variables (data),
  • the heap, so memory from malloc is visible to every thread,
  • the open files.

Each thread has things of its own, because each one is at a different place in the code, doing different calls:

  • its own stack, holding its local variables and return addresses,
  • its own registers, including its own program counter and stack pointer.

The kernel’s record for a thread is like a small PCB, usually called a TCB (thread control block).

Watch a process start with one thread and gain two more. Look at which boxes get copied (none of the shared ones) and which get created (one stack and one set of registers per thread).

One process, three threads

  1. One process, one thread A new process starts with a single thread, called main. It has the four shared regions (code, globals, heap, open files) and one stack of its own. Nothing is shared with anyone yet, because there is nobody else.
    Threads
    1
    Stacks
    1
    Shared regions
    4
    counter (global)
    0
  2. pthread_create: thread 2 starts The process asks for another thread. The kernel gives it its own stack and its own registers (a program counter and a stack pointer). It does not copy the code, globals, heap or open files: the new thread uses the ones that are already there.
    Threads
    2
    Stacks
    2
    Shared regions
    4
    counter (global)
    0
  3. pthread_create: thread 3 starts The process asks for another thread. The kernel gives it its own stack and its own registers (a program counter and a stack pointer). It does not copy the code, globals, heap or open files: the new thread uses the ones that are already there.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    0
  4. Thread 3 changes a global Thread 3 sets counter to 7. The global lives in the shared data region, so this is not a copy: it is the one and only counter.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7
  5. Every other thread sees the change Threads 1, 2 read counter and get 7 straight away. Sharing memory costs nothing, which is why threads are popular. It is also why two threads changing the same variable at the same time can go wrong (Module 4).
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7
  6. Local variables are private Each thread's local variable id lives on its own stack, so each thread has its own id: thread 1 has 1, thread 2 has 2, thread 3 has 3. No thread can see another one's locals by name.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7
  7. The other threads finish Threads 2 to 3 return. Each one's stack is freed. The shared regions stay, because main is still using them.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7
  8. main returns: the process ends When main returns, the process exits and every region is freed.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7

The shared regions are what makes threads attractive. A thread costs much less than a process to create, and two threads can work on the same data with no copying and no special channel. Press Try it and change the number of threads: the shared boxes stay the same while the stacks multiply.

But sharing has a price. If two threads change the same variable at the same time, the result can be wrong in a way that is hard to find. That is the subject of Module 4. For now, remember that every shared variable is a risk.

Threads in C

This program starts two threads with pthread_create. Each one prints its own id (a local on its own stack), and thread 2 sets the global shared. After pthread_join, which waits for a thread the way wait waits for a child, main reads the global.

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

int shared = 0;                         /* a global: every thread sees this one */

void *worker(void *arg) {
    int id = *(int *)arg;               /* a local: lives on this thread's own stack */
    printf("thread %d is running\n", id);
    if (id == 2) shared = 42;
    return NULL;
}

int main(void) {
    pthread_t t1, t2;
    int id1 = 1, id2 = 2;
    pthread_create(&t1, NULL, worker, &id1);   /* start worker(&id1) in a new thread */
    pthread_create(&t2, NULL, worker, &id2);
    pthread_join(t1, NULL);                    /* wait until it has finished */
    pthread_join(t2, NULL);
    printf("main sees shared = %d\n", shared);
    return 0;
}

Output (one run)

thread 1 is running
thread 2 is running
main sees shared = 42

Both workers ran the same function. main saw the value thread 2 stored, because it is the same variable. The two “running” lines can appear in either order: the threads run at the same time, and which one prints first is up to the scheduler. That is the same situation as the parent and child after a fork.

A crash takes everything with it

Processes protect each other. A bug in one cannot touch another’s memory, and when one crashes the others carry on. Threads do not have that protection: they share an address space, so a bad write by one thread can damage data every other thread relies on. For this reason the kernel treats a fatal fault in any thread as a fault of the whole process.

One thread crashes

  1. One process, one thread A new process starts with a single thread, called main. It has the four shared regions (code, globals, heap, open files) and one stack of its own. Nothing is shared with anyone yet, because there is nobody else.
    Threads
    1
    Stacks
    1
    Shared regions
    4
    counter (global)
    0
  2. pthread_create: thread 2 starts The process asks for another thread. The kernel gives it its own stack and its own registers (a program counter and a stack pointer). It does not copy the code, globals, heap or open files: the new thread uses the ones that are already there.
    Threads
    2
    Stacks
    2
    Shared regions
    4
    counter (global)
    0
  3. pthread_create: thread 3 starts The process asks for another thread. The kernel gives it its own stack and its own registers (a program counter and a stack pointer). It does not copy the code, globals, heap or open files: the new thread uses the ones that are already there.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    0
  4. Thread 3 changes a global Thread 3 sets counter to 7. The global lives in the shared data region, so this is not a copy: it is the one and only counter.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7
  5. Every other thread sees the change Threads 1, 2 read counter and get 7 straight away. Sharing memory costs nothing, which is why threads are popular. It is also why two threads changing the same variable at the same time can go wrong (Module 4).
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7
  6. Local variables are private Each thread's local variable id lives on its own stack, so each thread has its own id: thread 1 has 1, thread 2 has 2, thread 3 has 3. No thread can see another one's locals by name.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7
  7. Thread 2 uses a bad pointer Thread 2 writes through a pointer that is not valid memory. The CPU raises a fault and the kernel sends the process SIGSEGV. The kernel kills the whole process, not just thread 2: every thread lives in the same address space and the kernel cannot tell which other threads were relying on what was damaged.
    Threads
    3
    Stacks
    3
    Shared regions
    4
    counter (global)
    7
    Process
    killed

If you need one job to survive another’s crash, use separate processes. If you need jobs to share data quickly and trust each other, use threads.

In the real world

Linux does not have a separate kind of object for threads. Both processes and threads are tasks, created with the clone system call. clone takes flags that say what the new task shares with its creator. Share nothing, and you have made a process, as fork does. Share the address space, files and more, and you have made a thread. Each thread gets its own task ID, and the process ID is the ID of its first thread. This program creates two threads, then counts the tasks the kernel sees:

tasks.c
#define _GNU_SOURCE
#include <dirent.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>

void *worker(void *arg) {
    (void)arg;
    usleep(300000);                     /* stay alive while main counts */
    return NULL;
}

int main(void) {
    pthread_t t[2];
    for (int i = 0; i < 2; i++) pthread_create(&t[i], NULL, worker, NULL);
    int tasks = 0;
    DIR *d = opendir("/proc/self/task");        /* one entry per thread */
    struct dirent *e;
    while ((e = readdir(d)) != NULL)
        if (e->d_name[0] != '.') tasks++;
    closedir(d);
    printf("the kernel sees %d tasks in this one process\n", tasks);
    printf("main thread's id equals the process id: %s\n", syscall(SYS_gettid) == getpid() ? "yes" : "no");
    for (int i = 0; i < 2; i++) pthread_join(t[i], NULL);
    return 0;
}

Output (one run)

the kernel sees 3 tasks in this one process
main thread's id equals the process id: yes

Two threads plus main make three tasks. On a real system, ps -eLf lists every thread of every process.

Browsers are the textbook trade-off. Chrome and Firefox run web pages and other risky work in separate processes, so a crash or a security hole in one tab does not reach the rest, and use many threads inside each process for speed. :::

Quick check

Quick check

  1. Which of these do all the threads of one process share?
  2. What does each thread have that is its own?
  3. A bug in one thread makes it write through a bad pointer. Compared with a bug in one process, what is the difference?
  4. Why is creating a thread cheaper than creating a process?

Recap

  • A thread is a path of execution inside a process. Every process has at least one.
  • Threads share code, globals, heap and open files. Each thread has its own stack and registers.
  • Threads are cheaper than processes, and can share data with no copying.
  • Sharing is also the risk: simultaneous changes to one variable can go wrong (Module 4), and a crash in one thread ends the whole process.
  • On Linux, threads and processes are both tasks made with clone, which differ in what they share.

Next: with many processes and threads ready to run, the kernel must keep swapping which one is on the CPU. That swap has a precise recipe.

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion