Summary - Concurrency
- C++ course
- Advanced
- Lesson 24/83
- 5 min
Combine thread, mutex and async to write a parallel computation.
Summary - Concurrency
In this group you met five tools of C++ concurrency: std::thread for threads, std::mutex for mutual exclusion, std::lock_guard for RAII locking, std::async for background tasks and std::future for waiting on results. They all live in the <thread> and <future> headers.
Together these tools let you write programs that run in parallel and share data safely. Now you will write a small task that combines what you learned: two threads add to a shared counter protected by a lock_guard.
Practice Summary with thread + lock_guard
Declare global int counter = 0; and std::mutex m;. Write void add(int n) whose body is std::lock_guard<std::mutex> lk(m); counter += n;. In main start std::thread t1(add, 5); and std::thread t2(add, 3);, join both, then write std::cout << counter;.
Starter code
#include <iostream>
#include <thread>
#include <mutex>
int counter = 0;
std::mutex m;
// Write the add function
int main() {
// Start two threads, wait, print
return 0;
}Sample solution
#include <iostream>
#include <thread>
#include <mutex>
int counter = 0;
std::mutex m;
void add(int n) {
std::lock_guard<std::mutex> lk(m);
counter += n;
}
int main() {
std::thread t1(add, 5);
std::thread t2(add, 3);
t1.join();
t2.join();
std::cout << counter;
return 0;
}Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool is the RAII wrapper for a mutex?
- std::thread
- std::async
- std::future
- std::lock_guard Correct answer
Explanation: std::lock_guard is the RAII wrapper for a mutex.
2 Match each tool to its purpose
| Term | Meaning |
|---|---|
std::thread |
Thread |
std::mutex |
Mutual exclusion |
std::lock_guard |
RAII lock |
std::future |
Result wait |
3 Complete the lock_guard line
void add(int n) {
std::____<std::mutex> lk(m);
counter += n;
}
void add(int n) {
std::lock_guard<std::mutex> lk(m);
counter += n;
}
Explanation: std::lock_guard<std::mutex> lk(m); acquires the lock with RAII.