File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ all :
2+ clang++ -std=c++17 -g -O0 main.cpp -o main
3+
4+ debug :
5+ clang++ -std=c++17 -g -O0 main.cpp -o main && lldb ./main
6+
7+ run :
8+ clang++ -std=c++17 -g -O0 main.cpp -o main && ./main
9+
10+ clean :
11+ rm -rf main * .dSYM * .s
Original file line number Diff line number Diff line change 1+ ## Video Overview
2+
3+ - Previously, we talked about threads
4+ - What is a mutex?
5+ - Mutual exclusion (venn diagram, where the 2 circles don't meet)
6+ - Why do we need mutex?
7+ - Prevent race conditions + data corruption
8+ - Show how threads can overwrite data
9+ - How does mutex fix it?
10+ - Lock/unlock outside the for-loop
11+ - Why you need to be careful with mutexes?
12+ - Lock/unlock inside the for-loop
13+
14+ ## Titles
15+
16+ - What is a C++ Mutex and How Does it?
17+
18+ ## References
19+
20+ - ChatGPT and Gemini
Original file line number Diff line number Diff line change 1+ // #include <chrono>
2+ #include < iostream>
3+ #include < mutex>
4+ #include < thread>
5+
6+ using namespace std ;
7+
8+ std::mutex counter_mtx;
9+ int counter = 0 ;
10+
11+ void increment_counter () {
12+ counter_mtx.lock ();
13+ for (size_t i = 0 ; i < 1000000 ; i++) {
14+ counter++;
15+ }
16+ counter_mtx.unlock ();
17+ }
18+
19+ int main () {
20+ // cout << "start count: " << counter << endl;
21+ // std::thread t1(increment_counter);
22+ // std::thread t2(increment_counter);
23+ // t1.join();
24+ // t2.join();
25+ // cout << "end count: " << counter << endl;
26+
27+ cout << " start count: " << counter << endl;
28+ auto start = std::chrono::high_resolution_clock::now ();
29+ std::thread t1 (increment_counter);
30+ std::thread t2 (increment_counter);
31+ t1.join ();
32+ t2.join ();
33+ auto end = std::chrono::high_resolution_clock::now ();
34+ cout << " end count: " << counter << endl;
35+ std::chrono::duration<double , std::milli> elapsed = end - start;
36+ cout << " Function took: " << elapsed.count () << " ms" << endl;
37+
38+ return 0 ;
39+ }
You can’t perform that action at this time.
0 commit comments