0

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?

Marco Agnese
  • 349
  • 4
  • 15
  • 1
    You are writing a hot waitloop that burns 100% core. That's getting threading synchronization wrong in a drastic way, time to have a look-see at other synchronization mechanisms. Google "c++ countdownlatch". – Hans Passant Aug 11 '14 at 13:20

1 Answers1

5

The race in exhibited by your code is as follows: Once the last thread reaches the barrier, all threads are allowed to continue. However, as soon as the first thread reaches the barrier again, the condition for continuing is no longer true. Any threads that have not left the barrier by that point will be stuck.

An easy solution to this problem is the use of C++11's condition_variable. I posted a sample implementation not too long ago as part of this answer.

Community
  • 1
  • 1
ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
  • Very nice solution. The only thing I am missing is how to write the self-resetting. I mean, where should I put wait_count = 0? Because I thought that the correct place was after the notify_all() but this lead to a segmentation fault. – Marco Agnese Aug 11 '14 at 15:54