Find a course

Module 2: Processes, Threads and SchedulingLesson 4 of 1114 min

Threads and Concurrency

Understand how threads share a process, why they are cheaper than processes, the difference between concurrency and parallelism, and when threads help.

Step 1 of 13Learn

One process, many threads

A web browser tab loads images, runs JavaScript, decodes video and responds to your scrolling, all at the same time. If the program had only one sequence of execution, a slow image download would freeze the whole page. The solution is threads.

A thread is an independent sequence of execution inside a process. Every thread has its own:

  • Program counter: where it is in the code.
  • Registers: its working values.
  • Stack: its own chain of function calls and local variables.

But all threads in a process share:

  • The address space: code, global data and the heap.
  • Open files and other kernel resources.
  • The process's user identity and permissions.

That sharing is what makes threads useful and also what makes them dangerous. Two threads can cooperate on the same data structure without copying anything, because they see the same memory. But two threads can also change the same variable at the same time and corrupt it, a problem the next module tackles.

The kernel tracks each thread with a small thread control block holding its saved registers and state, alongside the process's PCB. On Linux, threads and processes are both tasks; a thread is simply a task that shares its address space with others.

Step 2 of 13Practice · Sort into groups

Which of these does each thread have for itself, and which are shared by all threads in a process?

Tap an item, then tap its group (or drag it there).

Step 3 of 13Learn

Why use threads instead of processes?

You could get similar effects by starting several processes. Threads win in three ways.

Cheaper to create and switch. A new thread needs a stack and a small control block; a new process needs a whole address space, page tables and kernel bookkeeping. Switching between threads of the same process doesn't change memory mappings, so the CPU's address translation caches stay valid.

Easy sharing. Threads communicate by reading and writing shared memory. Processes must use inter-process communication (IPC): pipes, sockets, message queues or explicitly shared memory regions, all of which take more setup.

Responsiveness. A program can put slow work, such as network requests or file loading, on background threads while one thread keeps the user interface responsive.

Processes still have a big advantage: isolation. A crashing thread usually takes its whole process down, along with every other thread in it. A crashing process leaves others untouched. That's why modern browsers such as Chrome and Firefox run separate tabs and sites in separate processes. A crash or security exploit in one site's renderer can't directly reach another site's memory.

The rule of thumb: use threads for cooperating tasks that trust each other and share lots of data; use processes when you want a fault or security boundary.

Step 4 of 13Compare

Threads vs. processes

AspectThreads (same process)Separate processes
MemoryShared address spacePrivate address spaces
Creating and switchingCheapMore expensive
CommunicationShared variables (needs locks)IPC: pipes, sockets, shared memory
A crashTakes down every threadStays inside one process
ExampleBrowser tab decoding video while scrollingBrowser running each site in its own process

Step 5 of 13Practice · What would you do?

What would you do?

You're designing a photo app. One feature applies a filter to a huge image using all CPU cores. Another feature opens untrusted image files downloaded from the internet, using a third-party decoding library known to have had security bugs. How should you structure them?

Step 6 of 13Learn

Concurrency vs. parallelism

Two words are often used as if they meant the same thing. They don't.

Concurrency means several tasks are in progress during the same period. On a single core, the OS can interleave three threads, running each for a few milliseconds in turn. They're concurrent, but at any instant only one is executing.

Parallelism means several tasks are executing at the same instant, which requires multiple cores or processors.

A chef cooking three dishes by switching between pans is concurrent. Three chefs each cooking one dish are parallel.

Concurrency is about structure: handling many things at once, such as a server juggling thousands of client connections that mostly sit waiting for the network. Parallelism is about speed: finishing a big computation sooner by splitting it across cores.

Threads help with both, but parallel speedup has limits. Amdahl's law says that if a fraction s of a program must run serially, the maximum speedup with N cores is 1 ÷ (s + (1 − s) ÷ N). With 10% serial code, even an infinite number of cores gives at most a 10 times speedup. Coordination costs, such as locking and moving data between core caches, usually push real speedups lower still.

Step 7 of 13Compare

Concurrency vs. parallelism

AspectConcurrencyParallelism
MeaningSeveral tasks in progress over a periodSeveral tasks executing at the same instant
Needs multiple cores?NoYes
Kitchen analogyOne chef switching between three pansThree chefs, one dish each
AboutStructure: dealing with many thingsSpeed: doing many things

Step 8 of 13Explore

Amdahl's law

x is the number of cores, s the serial fraction. Watch how quickly the curve flattens as s grows.

0102030 204060
Speedup with 16 cores
6.4 x
Upper limit
10 x

Step 9 of 13Practice · Work it out

A program is 20% serial. According to Amdahl's law, what is its speedup on 4 cores? Round to two decimals.

Step 10 of 13Practice · Chart

Amdahl's law with a 10% serial part

Tap the first core count where doubling the cores added less than 1.5 to the speedup.

Tap the point that answers the question, then press Check.

Amdahl's law with a 10% serial partLine chart with 7 categories: 1 core: 1; 2: 1.82; 4: 3.08; 8: 4.71; 16: 6.4; 32: 7.8; 64: 8.77.02468101 core248163264
Computed: speedup = 1 / (0.1 + 0.9 / cores). The ceiling is 1 / 0.1 = 10x.
Amdahl's law with a 10% serial part
ItemSpeedup
1 core1
21.82
43.08
84.71
166.4
327.8
648.77

Step 11 of 13Note

Step 12 of 13Practice · True or false

Running four threads on a single-core computer is an example of parallelism.

Step 13 of 13Practice · Choose one

Why does a thread switch within the same process usually cost less than a switch between two different processes?