Created
June 5, 2021 21:49
-
-
Save SlowPokeInTexas/4c9c9b5ac6418d089944bb8fa3a1a60b to your computer and use it in GitHub Desktop.
C++ WaitGroup a la Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <thread> | |
#include <condition_variable> | |
#include <mutex> | |
namespace CppWaitGroup | |
{ | |
using std::condition_variable; | |
using std::mutex; | |
using std::lock_guard; | |
using std::unique_lock; | |
class WaitGroup | |
{ | |
public: | |
WaitGroup(){}; | |
void Add( size_t count=1 ) | |
{ | |
lock_guard<mutex> lock( _mutex ); | |
_waitCount += count; | |
} | |
void Done() | |
{ | |
{ | |
lock_guard<mutex> lock( _mutex ); | |
_waitCount--; | |
} | |
_cond.notify_one(); | |
} | |
void Wait() | |
{ | |
unique_lock<mutex> lock(_mutex); | |
_cond.wait( lock, [this]{ return _waitCount == 0; } ); | |
} | |
protected: | |
size_t _waitCount=0; | |
mutex _mutex; | |
condition_variable _cond; | |
}; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requires C++ 17 or later