In the previous post I described Dekker’s algorithm. Its limitation is that it only works for 2 threads. I wanted it to work for N threads, but I can’t atomically check N-1 flags belonging to other threads 🙁 now what?
Instead of multiple
Complete listing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include <iostream> #include <atomic> #include <thread> #include <vector> using namespace std; const unsigned int COUNT = 5; const unsigned int THREADS = thread::hardware_concurrency(); const unsigned int THREAD_MASK = 0b1; int main(int argc, char** argv) { atomic_uint flag{0}; auto proc = [&](int t, unsigned int thread_mask) { for(int i = 0; i < COUNT;) { if(flag.fetch_or(thread_mask) == 0) { cout << "T" << t << " in critical section" << endl; ++i; } flag.fetch_xor(thread_mask); } }; vector<thread> vt; for(int i = 0; i < THREADS; ++i) vt.emplace_back(proc, i, THREAD_MASK << i); for(auto& t : vt) t.join(); return 1; } |
nice. I did not know about fetch_xor/or