Skip to content

Instantly share code, notes, and snippets.

@SlowPokeInTexas
Created June 5, 2021 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SlowPokeInTexas/4c9c9b5ac6418d089944bb8fa3a1a60b to your computer and use it in GitHub Desktop.
Save SlowPokeInTexas/4c9c9b5ac6418d089944bb8fa3a1a60b to your computer and use it in GitHub Desktop.
C++ WaitGroup a la Golang
#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;
};
};
@SlowPokeInTexas
Copy link
Author

Requires C++ 17 or later

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment