cpp-channels icon indicating copy to clipboard operation
cpp-channels copied to clipboard

race condition in WaitGroup class

Open yoda-jm opened this issue 6 years ago • 2 comments

I think that the implementation is racy, especially the Add/Done side. According to this link https://www.modernescpp.com/index.php/c-core-guidelines-be-aware-of-the-traps-of-condition-variables atomic variable modification should be made under the lock

yoda-jm avatar Feb 13 '20 17:02 yoda-jm

I think that the implementation is racy, especially the Add/Done side. According to this link https://www.modernescpp.com/index.php/c-core-guidelines-be-aware-of-the-traps-of-condition-variables atomic variable modification should be made under the lock

Agreed on this.

// this would be called from the main thread
void WaitGroup::Add(int i) {
  std::unique_lock<std::mutex> l(mu_);
  counter_ += i;
}

// this would be called from the worker thread
void WaitGroup::Done() {
  {
    std::unique_lock<std::mutex> l(mu_);
    counter_--;
  }
  cv_.notify_all();
}

// this would be called from the main thread
void WaitGroup::Wait() {
  std::unique_lock<std::mutex> l(mu_);
  cv_.wait(l, [&] { return counter_ <= 0; });
}

qiandu2006 avatar Jul 06 '20 09:07 qiandu2006

@qiandu2006 @yoda-jm thank you very much for your issue. I will update it once I have again a c++ development environment setup. Feel free to create a PR. I appreciate your review, thank you!

I leave it open until I have time to fix it or someone has sent a PR.

dragonquest avatar Jul 06 '20 20:07 dragonquest