Module 6 · Intermediate · Inside the hardware: from transistors to processors

Threads, multithreading and multitasking

Single-threading vs multithreading vs multitasking: processes and threads, time slicing, concurrency vs parallelism, race conditions, and threads in Python.

By theprogrammers team · · 11 min read

A railway station has ticket counters. With one counter and one clerk, the queue moves one person at a time, and if a passenger takes ten minutes to find their ID, everyone waits. Open four counters and four people are served at once. Or keep one clerk, but let them serve the next person while the slow passenger searches their bag. Those three set-ups are exactly the difference between single-threading, parallelism and concurrency, and computers use all three.

Your laptop runs a browser, a music player and VS Code at the same time; that's multitasking, organised by the operating system. Inside the browser, one part downloads a page while another responds to your clicks; that's multithreading. This lesson explains processes and threads, how one CPU core can appear to do many things at once, what can go wrong when threads share data, and how Python handles threads.

What you need first: what is an operating system? and stack and heap memory.

Key terms

  • Process: a running program, with its own memory given by the OS.
  • Thread: a sequence of instructions running inside a process. A process has at least one thread; threads in a process share its memory.
  • Single-threaded: a program that does one thing at a time, in one sequence.
  • Multithreaded: a program with several threads that can make progress at the same time.
  • Multitasking: the OS running many processes at once, by sharing CPU time between them.
  • Context switch: the OS pausing one thread and resuming another on the same core.
  • Concurrency: several tasks in progress at once, possibly taking turns on one core.
  • Parallelism: several tasks actually running at the same instant, on different cores.
  • Race condition: a bug where the result depends on the unpredictable timing of threads.

Programs, processes and threads

ProgramProcessThread
What it isA file of instructions on diskA running copy of a programOne line of execution inside a process
MemoryNone while not runningIts own, protected from other processesShares the process's heap; has its own stack
Examplechrome.exe on your SSDChrome runningChrome's thread that downloads a page, while another draws the screen
Cost to createRelatively highLower

Each thread has its own stack (its own function calls and local variables) and its own position in the code, but all threads in a process share the heap: the same lists, objects and global variables. That sharing makes threads cheap and quick to communicate, and it's also where their bugs come from.

Single-threaded programs

Most programs you write at first are single-threaded: one instruction after another, in order. If a step waits (for a file, a network reply, or the user to type), the whole program waits.

That's fine for scripts. It's a problem for an app with a window: if the only thread is busy downloading, nothing redraws the window or responds to clicks, and Windows marks it "Not responding". Apps avoid this by doing slow work in another thread.

Multitasking: how one core runs many programs

A single CPU core runs one thread at any instant. Yet even old single-core computers ran a music player and a word processor "at once". The OS does it by time slicing:

  1. A thread runs for a short time slice, typically a few milliseconds.
  2. A hardware timer interrupts the CPU, and the OS's scheduler takes over.
  3. The OS saves the thread's registers and position (a context switch), picks the next thread that's ready, restores its registers, and lets it run.
  4. Repeat, hundreds of times a second.

This is preemptive multitasking: the OS decides when to switch, so no program can hog the CPU. (Very old systems used cooperative multitasking, where each program had to give up the CPU voluntarily, and one misbehaving program could freeze the whole computer.)

Threads that are waiting for something, like a file or the network, aren't given time slices at all until their data arrives. That's why a computer with hundreds of processes open can still feel quick: most of them are asleep.

With several cores, the scheduler spreads threads across cores, so several really do run at the same instant.

Concurrency vs parallelism

ConcurrencyParallelism
MeaningSeveral tasks in progress at the same timeSeveral tasks executing at the same instant
Needs multiple cores?No; tasks can take turns on one coreYes
Ticket counter versionOne clerk switching between customers while each fills in a formFour clerks serving four customers
Good forWaiting on many things: network requests, files, usersHeavy calculation: video encoding, ML training, simulations

Concurrency is about structure (dealing with many things at once); parallelism is about execution (doing many things at once). A program can be concurrent without being parallel, and the reverse.

Hardware threads and hyper-threading

Many CPUs let each physical core run two hardware threads at once, called simultaneous multithreading (SMT), or Hyper-Threading in Intel's marketing. The core has two sets of registers and switches between threads in hardware whenever one is waiting for memory, so its adders and other parts stay busy.

That's why os.cpu_count() often reports double the number of physical cores (see CPU, GPU, RAM and storage). Two hardware threads on one core don't give double the speed; often 15 to 30% more, depending on the work.

Threads in Python

Python's threading module starts threads. Here, four simulated downloads each wait 0.3 seconds, first one after another, then in four threads:

import threading
import time

def download(file_number):
    time.sleep(0.3)                 # pretend we're waiting for the network

start = time.perf_counter()
for i in range(4):
    download(i)
one_thread = time.perf_counter() - start

start = time.perf_counter()
threads = [threading.Thread(target=download, args=(i,)) for i in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()                        # wait for each thread to finish
four_threads = time.perf_counter() - start

print("One thread took at least 1.2 s:", one_thread >= 1.2)
print("Four threads took under 0.6 s:", four_threads < 0.6)
One thread took at least 1.2 s: True
Four threads took under 0.6 s: True

One after another, the four waits add up to 4 × 0.3 = 1.2 seconds or a little more. In four threads, the program finishes in about the time of one download (around 0.3 seconds), because all four waits overlap. We print checks rather than exact times, because timings vary slightly between computers. start() begins a thread; join() waits for it to finish.

The GIL: threads and CPU-heavy Python

The standard Python interpreter (CPython) has a Global Interpreter Lock (GIL): only one thread can run Python code at a time. Threads still help when the work is mostly waiting (network, files, databases), because a waiting thread releases the GIL. But for pure Python calculation, threads don't run in parallel, so they don't speed it up.

Kind of workUseWhy
Waiting on I/O: downloads, API calls, database queriesthreading or asyncioWaiting threads release the GIL; waits overlap
Heavy calculation in Pythonmultiprocessing or concurrent.futures.ProcessPoolExecutorSeparate processes each have their own interpreter and GIL, so they use several cores
Heavy maths on arraysNumPy, pandas, PyTorchTheir C code releases the GIL and often uses several cores itself

Python 3.13 added an experimental free-threaded build with no GIL, which lets threads run Python code in parallel. It's optional and still maturing, so the table above remains the usual advice.

Race conditions and locks

Because threads share memory, two threads changing the same variable can interfere. count += 1 looks like one step, but it's really three: read count, add 1, write it back. If two threads both read 10, both add 1, and both write 11, one increase is lost. Whether that happens depends on exactly when each thread is paused: a race condition. These bugs are hard to find because they may appear only once in a thousand runs.

The fix is a lock (also called a mutex): only one thread can hold it at a time, so the read-add-write happens without interruption:

import threading

count = 0
lock = threading.Lock()

def add_many():
    global count
    for _ in range(100_000):
        with lock:                  # only one thread at a time inside this block
            count += 1

threads = [threading.Thread(target=add_many) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(count)
400000

With the lock, the total is always 4 × 100,000. Locks have their own danger: if thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1, both wait for ever. That's a deadlock. Simple rules help: hold locks briefly, and always take several locks in the same order.

Many programs avoid shared data altogether: each thread gets its own data, and threads pass results through a thread-safe queue (Python's queue.Queue).

Practice

  1. What's the difference between a process and a thread?
Show the answer

A process is a running program with its own memory, protected from other processes. A thread is a line of execution inside a process; threads in the same process share its heap memory but each has its own stack.

  1. A laptop has one core. Can it multitask? Can it run two threads in parallel?
Show the answer

It can multitask, by switching between threads every few milliseconds (concurrency). It can't run two threads at exactly the same instant (parallelism), unless the core supports two hardware threads, and even then they share one core's parts.

  1. A Python script downloads 50 web pages one after another and takes 50 seconds, mostly waiting. Would threads help? Would they help a script that spends 50 seconds calculating prime numbers in pure Python?
Show the answer

Threads would help the downloader a lot, since the waits overlap and waiting threads release the GIL. They wouldn't help the prime calculation in standard Python, because the GIL lets only one thread run Python code at a time; use multiprocessing to spread it across cores instead.

  1. Explain why count += 1 in two threads without a lock can lose updates.
Show the answer

It's three steps: read, add, write. If both threads read the same value before either writes, both write the same new value, so one increase is lost. A lock makes the three steps happen together for one thread at a time.

  1. What's a context switch, and why isn't it free?
Show the answer

It's the OS pausing one thread and resuming another on a core: saving the first thread's registers and position, and loading the second's. It takes time, and the new thread's data often isn't in the CPU cache yet, so too many threads switching too often slows a program down.

Interview questions

What is the difference between multitasking, multithreading and multiprocessing?

Multitasking is the OS running multiple tasks (processes) by sharing CPU time. Multithreading is one process running multiple threads that share its memory. Multiprocessing uses multiple processes, each with separate memory, often to use multiple cores; it also describes systems with multiple CPUs.

What is the difference between concurrency and parallelism?

Concurrency means multiple tasks make progress over overlapping time periods, possibly interleaved on one core. Parallelism means tasks execute simultaneously on multiple cores. Concurrency is a way of structuring a program; parallelism is a property of how it runs.

What is a deadlock, and how can you prevent it?

A deadlock is when two or more threads each wait for a resource held by another, so none can proceed. Prevent it by acquiring locks in a consistent global order, holding locks briefly, using timeouts, or designing to avoid shared locks, for example with message queues.

What is the GIL in Python?

The Global Interpreter Lock in CPython allows only one thread to execute Python bytecode at a time. It simplifies memory management but prevents CPU-bound Python threads from running in parallel. I/O-bound threads still benefit, and multiprocessing or C extensions are used for CPU-bound parallelism. Python 3.13 offers an experimental free-threaded build without the GIL.

Key takeaways

  • A process is a running program with its own memory; threads run inside it, sharing its heap, each with its own stack.
  • Multitasking means the OS shares CPU time between processes by time slicing and context switches.
  • Concurrency is many tasks in progress at once; parallelism is many running at the same instant on several cores.
  • Shared memory makes threads fast to communicate but causes race conditions; locks fix them but can deadlock.
  • In standard Python, use threads or asyncio for waiting-heavy work, and multiple processes for heavy calculation, because of the GIL.

Frequently asked questions

Is multithreading always faster?

No. It helps when work can overlap: waiting on I/O, or calculation split across cores. Too many threads add context-switching overhead, locks can make threads wait for each other, and in standard Python, CPU-heavy threads don't run in parallel at all.

What is hyper-threading?

Intel's name for simultaneous multithreading: one physical core runs two hardware threads, switching between them whenever one is stalled. It usually gives a modest speed-up, not double.

What is asyncio in Python?

A way to write concurrent code in a single thread. Functions marked async pause with await while waiting, letting other tasks run. It's well suited to programs that make many network requests at once, such as web servers and scrapers.

What to learn next

  1. Compare the chips that run all this in processor vs microcontroller.
  2. Find where your program spends its time in CPU profiling.
  3. Revise how the OS schedules processes in what is an operating system?