I have written a simple synchronization for threads but it deadlocks and I don't know hot ot fix it in a clever way.
I have a
std::atomic<int> count_;
declared in my main (it is initialized equal to 0) and each threads run this code
count_++;
while(!(count_%size_==0)); // wait until all the threads have reached this point
where
size_
is the number of threads launched (in my case 2). This synchronization code is run several times inside the threads (in my case 3).
Sometimes it works fine, but sometimes it deadlocks.
I think that sometimes, not at the first call of this barrier, a thread increments again the count_ before that the other thread test the condition leading to a deadlock.
How can I fix this issue without putting any delay function? Is there a better way to create a checkpoint inside thread?