Skip to content

Instantly share code, notes, and snippets.

@supr
Created April 13, 2019 22:28
Show Gist options
  • Save supr/76e39c1f446148f24319ea68c9346560 to your computer and use it in GitHub Desktop.
Save supr/76e39c1f446148f24319ea68c9346560 to your computer and use it in GitHub Desktop.
atomics_test.cc
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
#include <string>
usign namespace std;
atomic<int> lock(0);
atomic<int>& increment() {
atomic_fetch_add(&lock, 1);
return lock;
}
void decrement() {
atomic_fetch_sub(&lock, 1);
}
void aquire() {
while(increment() != 1) {
decrement();
}
}
void release() {
decrement();
}
void thr(void*) {
auto tid = this_thread::get_id();
while(true) {
cout << tid << " : Running" << endl;
aquire();
cout << tid << " : Got lock" << endl;
release();
cout << tid << " : Release lock" << endl;
}
}
int main(int argc, char** argv) {
auto conc = thread::hardware_concurrency();
if(argc > 1) {
conc = stoi(argv[1]);
}
vector<thread> v(conc);
for(size_t i = 0; i < v.size(); ++i) {
v[i] = thread(thr, nullptr);
}
for(size_t i = 0; i < v.size(); ++i) {
v[i].join()
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment