diff --git a/atomic.cpp b/atomic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..87c50bf093248ec12c908d9314f2d68e9b1edcab --- /dev/null +++ b/atomic.cpp @@ -0,0 +1,27 @@ +#include <array> +#include <thread> +#include <iostream> + +int main() { + constexpr auto n_threads = 10u; + std::atomic<int> counter = {0}; + std::array<std::thread, n_threads> threads; + + const auto increment = [](std::atomic<int>& i) { + // We don't care what order the the threads perform their increment operations. + i.fetch_add(1, std::memory_order_relaxed); + }; + + for (auto i = 0u; i < n_threads; ++i) { + threads[i] = std::thread(increment, std::ref(counter)); + } + + for (auto i = 0u; i < n_threads; ++i) { + threads[i].join(); + } + + std::cout << "Final value: " << counter << std::endl; + + return 0; +} +