Notify_all不唤醒等待线程
notify_all does not wake up wait thread
DBThread::DBThread() : running_(false)
{
}
DBThread::~DBThread()
{
if (thread_)
{
thread_->join();
}
}
void DBThread::Init()
{
thread_ = std::make_shared<std::thread>(std::bind(&DBThread::Run, this));
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [&] {return running_; });
std::cout << "Init success";
}
void DBThread::AddTask(std::shared_ptr<Delegate> task)
{
std::lock_guard<std::mutex> lock(mutex_);
task_queue_.push(task);
}
void DBThread::Run()
{
running_ = true;
cv_.notify_all();
while (true)
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [&] {return !task_queue_.empty(); });
std::cout << "run task" << std::endl;
}
}
我有两个线程,命名为A和B,A调用Init并等待B完全初始化,A有时挂起等待,即使running_为真。知道为什么会这样吗?
std::condition_variable::wait(lock, pred)
与
while (!pred()) {
wait(lock);
}
如果线程将running_
设置为true
并在检查谓词的时间之间调用notify_all()
,但在调用wait之前,则通知将丢失,等待将等待到另一个通知到来。最简单的修复方法是:
void DBThread::Run()
{
std::unique_lock<std::mutex> lock(mutex_);
running_ = true;
cv_.notify_all();
while (true)
{
cv_.wait(lock, [&] {return !task_queue_.empty(); });
std::cout << "run task" << std::endl;
}
}
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 虚假唤醒是否会解锁所有等待线程,甚至是不相关的线程?
- 视频在唤醒其他线程时输入设备断开连接
- 等待线程的最佳方式是什么
- std::thread从函数启动,无需等待线程完成
- 带有共享缓冲区的两个等待线程(生产者/消费者)
- std::condition_variable::notify_one() 不会唤醒等待线程
- pthread_cond_wait唤醒多线程示例
- Boost::线程 / C++11 std::thread,想要唤醒工作线程的条件
- 在退出进程时等待线程完成
- 如何正确等待线程中的信号
- 如何等待线程直到它开始运行
- 在纯虚拟类的析构函数中等待线程死亡会导致运行时错误
- 更改可报警/可等待线程的上下文
- C++11 std::线程并等待线程完成
- 我如何在Qt中等待线程完成而不阻塞其执行
- Notify_all不唤醒等待线程
- 如何使用boost条件变量来等待线程完成处理
- 等待线程结束(c++)
- std::condition_variable – 通知一次,但等待线程唤醒两次