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完全初始化,即使running_为true,A有时会挂起等待。不知道为什么会发生这种情况。任何帮助都将受到赞赏。< / p>
答案 0 :(得分:2)
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;
}
}