In C++, concurrency can lead to complexities, especially when multiple threads access shared resources. Using mutexes, locks, and lock guards is essential for managing these accesses safely. A mutex (short for mutual exclusion) is a synchronization primitive that prevents multiple threads from accessing the same resource at the same time. Locks provide a way to acquire a mutex and automatically release it when no longer needed. The `std::lock_guard` is a convenient RAII-style mechanism that locks a mutex upon creation and unlocks it upon destruction.
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int sharedCounter = 0;
void incrementCounter() {
std::lock_guard<std::mutex> lock(mtx); // Locking the mutex
++sharedCounter;
std::cout << "Counter: " << sharedCounter << std::endl;
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?