-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.cpp
More file actions
36 lines (29 loc) · 922 Bytes
/
Copy pathmutex.cpp
File metadata and controls
36 lines (29 loc) · 922 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Compile and run:
// clang++ -std=c++20 -O0 -Wall -Wextra mutex.cpp -o mutex
// ./mutex
// clang++ -std=c++20 -O1 -fsanitize=address mutex.cpp -o mutex_asan
// ./mutex_asan
#include <iostream>
#include <mutex>
#include <thread>
int counter = 0; // Shared counter
std::mutex mtx; // Mutex to protect shared resource
// Thread A function (uses mutex)
void threadA() {
std::lock_guard<std::mutex> lock(mtx); // Lock mutex
counter++; // Increment the counter
std::cout << "Thread A incremented counter to: " << counter << "\n";
}
// Thread B function (uses mutex)
void threadB() {
std::lock_guard<std::mutex> lock(mtx); // Lock mutex
counter++; // Increment the counter
std::cout << "Thread B incremented counter to: " << counter << "\n";
}
int main() {
std::thread tA(threadA);
std::thread tB(threadB);
tA.join();
tB.join();
return 0;
}