Skip to content

Instantly share code, notes, and snippets.

@yuki-takeichi
Last active June 22, 2019 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuki-takeichi/e7f102cfdf3f7e3dc372fdce2640295a to your computer and use it in GitHub Desktop.
Save yuki-takeichi/e7f102cfdf3f7e3dc372fdce2640295a to your computer and use it in GitHub Desktop.
spinlock_false.cpp
#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