Condition_variable, mutex and flag in one structure

Is it possible to combine all three variables into one structure?

struct lock_struct
{
    std::mutex mutex;
    std::conditional_variable cv;
    bool flag;
};

Are there any hidden synchronization issues with this approach? I do not intend to change the structure myself, only its fields.

By the way, should I use boolor std::atomic<bool>when working with a flag std::condition_variable?

Edit: implemented based on responses.

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 this is the correct implementation.

+4
source share
1 answer

Is it possible to combine all three variables into one structure?

Yes.

Are there any hidden synchronization issues with this approach?

The definition of the structure does not describe or apply the intended use. Since all members are publicly available, nothing prevents misuse or unintentional use.

class , -.

, bool std::atomic<bool> std::condition_variable

bool , bool . , .

: std::atomic<bool> , , , :

Thread 1             |  Thread 2
                     |  check the bool
modify the bool      |
signal the condition |  <notification not received>
                     |  wait on the codition
+3

Source: https://habr.com/ru/post/1690227/


All Articles