example3_memory_ordering.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 <atomic>
#include <thread>
#include <iostream>
#include <vector>

std::atomic_flag lock = ATOMIC_FLAG_INIT;
int shared_resource = 0;

void increment_resource() {
    for (int i = 0; i < 100; ++i) {
        while (lock.test_and_set(std::memory_order_acquire)) { } // Spin lock
        shared_resource++;
        lock.clear(std::memory_order_release);
    }
}

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

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

    std::cout << "Final shared_resource value: " << shared_resource << std::endl;

    return 0;
}
Back to atomic