Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 66 ยท Threads and Concurrency

What Is a Thread?

Learn what a thread is, what threads share and what they keep private, how threads differ from processes, and why they make programs responsive, with runnable simulations.

A process owns resources (memory, files). A thread is a path of execution inside a process. Every process starts with one thread, but it can create more, and all of them run in the same address space. Each thread has its own program counter, registers and stack, so each can be at a different place in the code, while they all see the same global variables, heap and open files.

Threads exist because processes are heavy: creating one, switching between them and sending data between them all cost a lot. When a program wants to do several things at once (a browser downloading while rendering, a server handling many clients) threads give concurrency at a fraction of the cost. This lesson explains what threads share and keep private, compares them with processes, and shows how shared data makes threads both powerful and dangerous.

One process, several threads

Shared Code, globals, heap, open files.
Private Registers, program counter, stack.

A thread is sometimes called a lightweight process.

1 / 2

What threads share and what they do not

flowchart LR
    subgraph Process
      direction TB
      SH["Shared: code, data, heap, open files, signal handlers"]
      T1["Thread 1: registers, PC, stack"]
      T2["Thread 2: registers, PC, stack"]
      T3["Thread 3: registers, PC, stack"]
    end
    SH --- T1
    SH --- T2
    SH --- T3

Each thread has its own stack and CPU state; everything else belongs to the process.

A thread's private part is stored in a thread control block (TCB), a small cousin of the PCB: thread ID, register set, stack pointer, state and priority. Because the TCB is small and no memory map changes, creating a thread and switching between threads of one process is much cheaper than for processes (see context switching).

Threads versus processes

Aspect Process Thread
Address space Own private space Shared with the other threads of the process
Creation cost High Low
Context-switch cost High (page tables, TLB) Lower
Communication IPC needed (pipes, sockets) Read and write shared variables
Isolation Strong: a crash stays in the process Weak: one thread's bad pointer can crash all
Resources Own file table, memory Shared

The weak isolation is the flip side of cheap sharing: when several threads modify the same data without coordination, results become unpredictable. This is the race condition, treated fully in the Synchronization chapter.

Seeing "shared" and "private" in code

Python's threads cannot start inside the browser sandbox this lesson runs in, so the demo uses generator functions as cooperative stand-ins for threads. The idea carries over directly. A module-level list is shared by every thread, while each generator's local variables are private (like a stack).

Python Shared heap, private stacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both workers appended to the same shared_log, but their local_sum values never mixed.

How the same code looks with real threads

On a normal Python installation you would write this with the threading module. It is shown read-only here because the in-browser interpreter has no OS threads.

Python
import threading

def worker(name, items):
    print(name, "sum =", sum(items))

threads = [threading.Thread(target=worker, args=("T1", [1, 2, 3])),
           threading.Thread(target=worker, args=("T2", [10, 20]))]
for t in threads: t.start()   # both now run concurrently
for t in threads: t.join()    # wait for them to finish

The same shape appears in every language: create a thread with a function to run, start it, and join it when you need its result (Java's Thread, C's pthread_create/pthread_join, Go's goroutines).

Why a thread beats a process for some jobs

Imagine a text editor. One thread handles typing, another autosaves, another runs spell-check. With processes, the spell-checker would need its own copy of the document or an IPC channel to read it. With threads, all three simply read the same document structure. The following snippet estimates the memory cost, treating the document as 50 MB and the thread stack as 1 MB.

Python Cost of sharing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real systems use copy-on-write and shared libraries, so the processes' real cost is lower, but the principle stands: threads share more, so they cost less.

Thread life cycle

A thread has states like those of a process: new, runnable (ready), running, blocked (waiting for I/O or a lock) and terminated. When one thread blocks on I/O, the other threads of the process can still run. This is a key benefit: a single-threaded program freezes entirely during a slow operation, but a multithreaded one only blocks the thread that is waiting.

Common thread operations

Operation Meaning POSIX name
Create Start a thread running a function pthread_create
Join Wait for a thread to finish and get its result pthread_join
Exit End the calling thread pthread_exit
Yield Give up the CPU voluntarily sched_yield
Cancel Ask another thread to stop pthread_cancel
Detach Tell the system to reclaim the thread automatically pthread_detach

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these is private to each thread?

    Each thread has its own stack, registers and program counter. Code, globals, heap and files are shared.
  2. 2. Why are threads cheaper than processes?

    Creating a thread needs no new address space, and switching between threads of one process avoids page-table changes.
  3. 3. What is the main risk of threads sharing memory?

    Concurrent modification of shared data without coordination gives unpredictable results.
  4. 4. In a multithreaded program, one thread blocks on a network read. What happens to the other threads?

    Only the blocked thread waits; the others remain runnable.

Summary

  • A thread is an execution path inside a process with its own stack, registers and program counter.
  • Threads share code, global data, the heap and open files, which makes them cheap but also risky.
  • Compared with processes, threads are faster to create and switch and easier to coordinate, but offer weaker isolation.
  • A blocked thread does not stop its siblings, which keeps applications responsive.

Next: Multithreading Models