Is to ok to combine all three variables into one struct?
struct lock_struct
{
std::mutex mutex;
std::conditional_variable cv;
bool flag;
};
Are there any hidden synchronization problems with this approach? I do not intend to modify struct itself, only it's fields.
By the way, should I use bool
or std::atomic<bool>
when dealing with std::condition_variable
's flag?
Edit: implemented it based on the answers.
class ConditionLock
{
public:
void wait();
void notify();
bool getFlag() const;
private:
mutable std::mutex _mutex;
std::condition_variable _cv;
bool flag;
};
void ConditionLock::wait()
{
std::unique_lock<std::mutex> lock(_mutex);
_cv.wait(lock, [&] { return flag; });
}
void ConditionLock::notify()
{
std::unique_lock<std::mutex> lock(_mutex);
flag = true;
lock.unlock();
_cv.notify_all();
}
bool ConditionLock::getFlag() const
{
std::lock_guard<std::mutex> lock(_mutex);
return flag;
}
I hope it's a correct implementation.