【发布时间】:2023-11-02 00:34:01
【问题描述】:
为简单起见,假设我们只有一个条件变量来匹配由布尔值反映的单个条件。
1) 为什么std::condition_variable::wait(...) 在发送“通知”取消睡眠后再次锁定互斥锁?
2) 看到“1)”中的行为,这是否意味着当您执行std::condition_variable::notify_all 时,它只会使所有等待的线程都被解除阻塞/唤醒......但是按顺序 而不是一次全部?如果是这样,有什么办法可以一次性完成?
3) 如果我只关心线程在满足条件之前处于休眠状态,而不关心任何互斥量获取,我该怎么办?是否有替代方案或是否应该围绕这个问题破解当前的std::condition_variable::wait(...) 方法?
如果要使用“hackery”,这个函数是否可以在一个条件下解除阻塞所有等待线程,并且可以从任何(每个线程)线程调用它:
//declared somehwere and modified before sending "notify"(ies)
std::atomic<bool> global_shared_condition_atomic_bool;
//the single(for simplicity in our case) condition variable matched with the above boolean result
std::condition_variable global_shared_condition_variable;
static void MyClass:wait()
{
std::mutex mutex;
std::unique_lock<std::mutex> lock(mutex);
while (!global_shared_condition_atomic_bool) global_shared_condition_variable.wait(lock);
}
它会像这样从随机的“等待”线程中调用:
void random_thread_run()
{
while(someLoopControlValue)
{
//random code...
MyClass:wait(); //wait for whatever condition the class+method is for.
//more random code...
}
}
编辑:
门类
#ifndef Gate_Header
#define Gate_Header
#include <mutex>
#include <condition_variable>
class Gate
{
public:
Gate()
{
gate_open = false;
}
void open()
{
m.lock();
gate_open = true;
m.unlock();
cv.notify_all();
}
void wait()
{
std::unique_lock<std::mutex> lock(m);
while (!gate_open) cv.wait(lock);
}
void close()
{
m.lock();
gate_open = false;
m.unlock();
}
private:
std::mutex m;
std::condition_variable cv;
bool gate_open;
};
#endif
【问题讨论】:
标签: c++ multithreading c++11 blocking condition-variable