Created
April 28, 2020 10:09
-
-
Save cculianu/7dde6f434ec153501e520ee1c774cecd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
#include <iomanip> | |
#include <thread> | |
#include <atomic> | |
#include <mutex> | |
#include <condition_variable> | |
#include <memory> | |
int main(int argc, char *argv[]) | |
{ | |
const auto ORDER = argc < 2 ? std::memory_order_relaxed : std::memory_order_seq_cst; | |
std::cout << "Memory order: " << int(ORDER) << '\n'; | |
std::atomic_long var{0}; | |
const auto iters = 100'000'000; | |
const auto thrds = 10; | |
const long expected = iters * thrds; | |
using Atom = std::atomic<uint8_t>; | |
auto atoms = std::make_unique<Atom[]>(expected); | |
std::cout << "Iterating " << iters << " times with " << thrds << " threads ...\n"; | |
const auto f = [&var, &atoms, ORDER]() { | |
for (int i = 0; i < iters; ++i) | |
atoms[var.fetch_add(1, ORDER)].fetch_add(1, ORDER); | |
}; | |
std::vector<std::thread> v; | |
for (int i = 0; i < thrds; ++i) | |
v.emplace_back(f); | |
for (auto& t : v) | |
t.join(); | |
std::cout << "Final value: " << var.load() << " is expected: " << std::boolalpha << (var.load() == expected) << '\n'; | |
std::cout << "Scanning ... " << std::flush; | |
long failed = -1; | |
for (int64_t i = 0; i < expected; ++i) { | |
if (atoms[i].load() != 1) { | |
failed = i; | |
break; | |
} | |
} | |
if (failed < 0) | |
std::cout << "All ok!\n"; | |
else | |
std::cout << "Failed at " << failed << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment