example1_basic_usage.cpp

 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
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>

std::mutex mtx;
int shared_value = 0;

void increment(int id) {
    for (int i = 0; i < 1000; ++i) {
        mtx.lock();
        ++shared_value;
        mtx.unlock();
    }
    std::cout << "Thread " << id << " finished.\n";
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 10; ++i) {
        threads.emplace_back(increment, i);
    }

    for (auto& t : threads) {
        t.join();
    }

    std::cout << "Final value: " << shared_value << std::endl;
    return 0;
}
Back to mutex