Created
December 30, 2022 22:44
-
-
Save Aposhian/6d130b25892e3be382c0707dcfdf7045 to your computer and use it in GitHub Desktop.
demo how std::atomic can fix race conditions
This file contains hidden or 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 <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