Skip to content

Operating Systems 03 threads

Mugundan edited this page Nov 27, 2026 · 1 revision

Threads

Relevant source files

The following references were used as context for generating this wiki page:

A thread is one flow of execution inside a process. A process starts with one thread; it can create more, and all of them share the process's memory and open files while each keeps its own registers and stack. Threads let one program do several things at once, for example a browser downloading a page while still responding to clicks.

Code on this page is illustrative C using POSIX threads (pthread).

Purpose and Scope

This page covers what threads share and what each owns, threads versus processes, user-level versus kernel-level threads and the threading models, thread pools, and why threads need synchronization. Locks themselves are on Synchronization.

The Shared Office Analogy

Office Process with threads
One office (rooms, filing cabinets, phone line) One process: address space, open files
Several workers in that office Several threads
Each worker's own notepad and current task Each thread's own registers, PC and stack
Everyone can open every filing cabinet Every thread can read and write all the process's memory
Two workers editing the same file at once A race condition: needs a lock

A separate process would be a separate office: safer, but sharing papers means posting them (IPC).

What Threads Share and Own

flowchart TB
    subgraph P["One process"]
        direction TB
        SH["Shared by all threads:<br/>code, globals, heap,<br/>open files, signal handlers, PID"]
        subgraph T1["Thread 1"]
            R1["registers, PC"]
            S1["own stack"]
        end
        subgraph T2["Thread 2"]
            R2["registers, PC"]
            S2["own stack"]
        end
        subgraph T3["Thread 3"]
            R3["registers, PC"]
            S3["own stack"]
        end
    end
Loading
Shared (per process) Private (per thread)
Code (text) Program counter
Global and static variables Registers
Heap Stack (local variables, call frames)
Open file descriptors Thread ID
Current directory, user ID Thread-local storage (thread_local)
Signal handlers Signal mask, scheduling state

Trap: a thread's stack is private by convention, not protected. Another thread holding a pointer to it can still read or overwrite it.

Threads versus Processes

Process Thread
Memory Own address space Shares the process's address space
Creation cost Higher (new page tables, PCB) Lower
Context switch Slower: page table and TLB change Faster: same address space
Communication IPC through the kernel Just read and write shared variables
A crash (bad pointer) Kills only that process Kills the whole process, all threads
Isolation Strong None between threads

Typical choices: browsers use a process per tab for isolation and threads inside each; servers use a pool of threads for speed.

Sources: Wikipedia: Thread (computing)

Creating Threads

// illustrative
#include <pthread.h>
#include <stdio.h>

void *worker(void *arg) {
    int id = *(int *)arg;
    printf("hello from thread %d\n", id);
    return NULL;
}

int main(void) {
    pthread_t t[4];
    int ids[4];
    for (int i = 0; i < 4; i++) {
        ids[i] = i;                      // one slot per thread, not &i
        pthread_create(&t[i], NULL, worker, &ids[i]);
    }
    for (int i = 0; i < 4; i++)
        pthread_join(t[i], NULL);        // wait for each thread
    return 0;
}

The output order of the four lines can differ from run to run: the scheduler decides which thread runs when.

Trap: passing &i to every thread is a classic bug; all threads share one i that keeps changing.

User-Level and Kernel-Level Threads

User-level threads Kernel-level threads
Managed by A library in the process The kernel
Kernel knows about them? No: sees one thread Yes: schedules each one
Switch cost Very cheap (no system call) Needs the kernel
One thread blocks on I/O The whole process blocks Only that thread blocks
Use multiple cores No Yes

Threading Models

flowchart LR
    subgraph M1["Many-to-one"]
        u1["U"] --> k1["K"]
        u2["U"] --> k1
        u3["U"] --> k1
    end
    subgraph OO["One-to-one"]
        a1["U"] --> b1["K"]
        a2["U"] --> b2["K"]
        a3["U"] --> b3["K"]
    end
    subgraph MM["Many-to-many"]
        c1["U"] --> d1["K"]
        c2["U"] --> d1
        c3["U"] --> d2["K"]
        c4["U"] --> d2
    end
Loading
Model Description Example
Many-to-one All user threads on one kernel thread Old "green threads"
One-to-one Each user thread is a kernel thread Linux pthreads, Windows threads
Many-to-many M user threads multiplexed on N kernel threads Go goroutines, Erlang processes (runtime schedulers)

Thread Pools

Creating a thread for each request wastes time and can create too many threads. A thread pool creates a fixed set of worker threads once; work items go into a queue and idle workers take them.

flowchart LR
    R1["Request"] --> Q["Work queue"]
    R2["Request"] --> Q
    R3["Request"] --> Q
    Q --> W1["Worker 1"]
    Q --> W2["Worker 2"]
    Q --> W3["Worker 3"]
Loading

The queue itself is a producer-consumer buffer, see Synchronization.

Concurrency versus Parallelism

Meaning Needs multiple cores?
Concurrency Several tasks make progress over the same period, possibly by taking turns No
Parallelism Several tasks run at the same instant Yes
flowchart TB
    subgraph C["Concurrent on 1 core"]
        c["A A B B A B A A"]
    end
    subgraph P["Parallel on 2 cores"]
        p1["core 0: A A A A"]
        p2["core 1: B B B B"]
    end
Loading

Why Threads Need Care

Because threads share memory, two threads updating the same variable can interfere:

// illustrative: two threads each run this 1,000,000 times
counter++;          // load, add 1, store: three steps, not one

The final value is often less than 2,000,000, because both threads can load the same old value before either stores. Fixing this is the subject of Synchronization.

Common Traps

  • Threads share the heap and globals but not the stack or registers.
  • A segfault in one thread kills the whole process.
  • Output order between threads is not guaranteed without synchronization.
  • User-level threads alone cannot use more than one core.

Interview Questions

  1. Process vs thread? A process has its own address space; threads within a process share it, each with its own registers and stack. Threads are cheaper to create and switch but give no isolation.
  2. What do threads in one process share? Code, globals, heap, open files, signal handlers. Not stacks, registers or program counters.
  3. Why is a thread switch cheaper than a process switch? The page table stays the same, so there is no address-space switch and the TLB and caches stay warm.
  4. User vs kernel threads? User threads are managed by a library and invisible to the kernel; cheap but one blocking call blocks all, and no multicore. Kernel threads are scheduled individually by the kernel.
  5. Concurrency vs parallelism? Concurrency is dealing with many things at once (interleaving); parallelism is doing many things at once (multiple cores).
  6. Why use a thread pool? It avoids the cost of creating threads per task and bounds the number of threads.

Key Points

  • A thread is an execution flow inside a process: own registers, PC and stack; shared memory and files.
  • Threads are cheaper than processes but give no isolation; shared data needs synchronization.
  • Linux uses one-to-one kernel threads; runtimes like Go multiplex many user threads on few kernel threads.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally