一个结构中的condition_variable,mutex和flag

Cor*_*Ale 6 c++ multithreading struct synchronization c++11

可以将所有三个变量合并为一个结构吗?

struct lock_struct
{
    std::mutex mutex;
    std::conditional_variable cv;
    bool flag;
};
Run Code Online (Sandbox Code Playgroud)

这种方法有任何隐藏的同步问题吗?我不打算修改struct本身,只修改它的字段.

顺便问一下,我应该使用boolstd::atomic<bool>处理std::condition_variable国旗?

编辑:根据答案实施.

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;
}
Run Code Online (Sandbox Code Playgroud)

我希望这是一个正确的实现.

Max*_*kin 5

可以将所有三个变量合并为一个结构吗?

是.

这种方法有任何隐藏的同步问题吗?

结构定义未描述或强制执行其预期用途.由于所有成员都可公开访问,因此无法防止错误或无意使用.

更安全的定义是使其成为class没有公共数据成员但是公共成员函数.

顺便说一句,我应该使用boolstd::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
Run Code Online (Sandbox Code Playgroud)