Caffeinated Coder
Book an appointment
Lesson 26 · Building and performance

Threads and atomics

A thread is one path through your program, and the threads of a program share its memory. Start two threads that each add 1 to a shared counter 100000 times, and watch why a plain int can come out too low: ++ is really a load, an add and a store, so two threads can lose an update. That is a data race. Then make the counter a std::atomic<int>, wait for the threads with join(), and get 200000 every time.

12 min11 steps5 questionsAdvanced
Fig 26 · Interactive
Loading figure…
or ← →

Quiz Unlocks after the last step.