C++ Intermediate · Lesson 10 of 27
Multithreading: std::thread, std::mutex and std::lock_guard
Starting threads, joining them, data races and protecting shared data.
Estimated time · 60–90 min
Learning goals
What you will understand
- Explain multithreading: std::thread, std::mutex and std::lock_guard in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
std::thread starts a function on a new thread. You must join() it (wait for it to finish) or detach() it before the thread object is destroyed; joining is almost always right. Threads share memory, so two threads changing the same variable without protection is a data race and is undefined behaviour.
A std::mutex lets only one thread into a critical section at a time. Never call lock() and unlock() by hand; use std::lock_guard (or std::scoped_lock), which unlocks in its destructor. Keep the locked section short and never block on slow I/O while holding it. Compile with -pthread.
Guided lesson
Work through these steps
- 1.
Read the multithreading: std::thread, std::mutex and std::lock_guard example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
#include <thread>
// Header for std::thread.
#include <mutex>
// Header for std::mutex and lock_guard.
std::mutex m;
// Guards the shared counter.
int samples = 0;
// Shared data touched by two threads.
auto work = [&] {
// A lambda that each thread will run; & captures m and samples by reference.
for (int i = 0; i < 1000; ++i) {
// Do 1000 increments.
std::lock_guard<std::mutex> lock{m};
// Lock now; the destructor unlocks at the end of each iteration.
++samples;
// Safe: only one thread is here at a time.
}
// End of the loop body.
};
// End of the lambda.
std::thread a{work}, b{work};
// Start two threads running the same work.
a.join(); b.join();
// Wait for both to finish before reading the result.
std::cout << samples << '\n';
// Always prints 2000; without the mutex the result would vary.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Messages between nodes
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Multithreading: std::thread, std::mutex and std::lock_guard. Expected result: 2000
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
#include <mutex>
#include <thread>
int main() {
std::mutex m;
int samples = 0;
auto work = [&] {
for (int i = 0; i < 1000; ++i) {
// TODO: lock m with a lock_guard, then increment samples
}
};
std::thread a{work}, b{work};
a.join();
b.join();
std::cout << samples << '\n';
return 0;
}Expected output
2000Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <mutex>
#include <thread>
int main() {
std::mutex m;
int samples = 0;
auto work = [&] {
for (int i = 0; i < 1000; ++i) {
std::lock_guard<std::mutex> lock{m};
++samples;
}
};
std::thread a{work}, b{work};
a.join();
b.join();
std::cout << samples << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Run the example without the mutex and record the results over 10 runs. Add the lock_guard, then build with -fsanitize=thread -pthread and confirm ThreadSanitizer reports the race only in the unprotected version.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.