12.6 — Intro to multithreading
Doing two things at once#
Modern computers have several cores: little brains that can work at the same time. A thread is one line of work. Using several threads lets a program do several things at once.
Starting a thread#
#include <iostream>#include <thread> void countTo(int n, char tag){ for (int i { 1 }; i <= n; ++i) std::cout << tag << i << ' ';} int main(){ std::jthread worker { countTo, 5, 'A' }; // runs at the same time as main countTo(5, 'B'); return 0; // a jthread waits for its work to finish automatically}B1 A1 B2 B3 A2 A3 B4 A4 A5 B5The order changes every run — the two threads really are running side by side.
A thread that automatically waits ("joins") for its work to finish when it goes away (C++20). The older std::thread needs you to call .join() yourself.
The big danger: sharing#
If two threads change the same variable at the same time, the result can be wrong. This is called a data race.
int counter { 0 };auto addLots { [&counter]() { for (int i { 0 }; i < 100'000; ++i) ++counter; } }; { std::jthread a { addLots }; std::jthread b { addLots };}std::cout << counter; // should be 200000, but often isn't!Fix: std::atomic#
For simple counters, std::atomic makes each change safe:
#include <atomic> std::atomic<int> counter { 0 };// ... same code as before ...std::cout << counter; // always 200000For bigger shared data, a std::mutex lets only one thread at a time into a piece of code.
Threads are powerful but tricky. Bugs can appear only sometimes, which makes them very hard to find. Get comfortable with the rest of C++ first, and share as little data between threads as you can.
Tip: press ← / → to move between lessons, / to search.