Skip to content

Instantly share code, notes, and snippets.

@Aposhian
Created December 30, 2022 22:44
Show Gist options
  • Save Aposhian/6d130b25892e3be382c0707dcfdf7045 to your computer and use it in GitHub Desktop.
Save Aposhian/6d130b25892e3be382c0707dcfdf7045 to your computer and use it in GitHub Desktop.
demo how std::atomic can fix race conditions
#include <atomic>
#include <thread>
#include <iostream>
#include <string>
static constexpr int ITERATIONS = 1000000;
int main() {
// std::atomic<long long> num{0};
long long num{0};
auto increment_num = [&num]() {
for (int i = 0; i < ITERATIONS; ++i) {
++num;
}
};
auto t1 = std::thread(increment_num);
auto t2 = std::thread(increment_num);
t2.join();
t1.join();
std::cout << std::to_string(num) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment