Last active
June 22, 2019 16:00
-
-
Save yuki-takeichi/e7f102cfdf3f7e3dc372fdce2640295a to your computer and use it in GitHub Desktop.
spinlock_false.cpp
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 <cassert> | |
#include <iostream> | |
#include <atomic> | |
#include <thread> | |
#include <vector> | |
#include <string> | |
using namespace std; | |
atomic_bool l; | |
atomic_int i(0); | |
void check() { | |
assert(i.load() == 0); | |
i++; | |
assert(i.load() == 1); | |
i--; | |
assert(i.load() == 0); | |
} | |
void hoge(int i) { | |
for (int n = 0; n < 1000000; n++) { | |
// Bug! Should be: `while (l.exchange(true));` | |
while (l.load()); l.store(true); | |
check(); | |
l.store(false); | |
} | |
} | |
int main(int argc, char *argv[]) { | |
if (argc != 2) return -1; | |
string n(argv[1]); | |
int N = stoi(n); | |
l.store(false); | |
vector<thread> v; | |
for (int i = 0; i < N; i++) { | |
v.push_back(thread(hoge, i)); | |
} | |
for (int i = 0; i < N; i++) { | |
v[i].join(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment