本文介绍了为什么std :: condition_variable的notify和wait函数都需要一个锁定的互斥锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我不断的努力去了解 std :: contion_variable 我遇到以下。在上,它显示以下内容:

  void print_id(int id){
std :: unique_lock< std :: mutex> lck(mtx);
while(!ready)cv.wait(lck);
// ...
std :: cout<< thread<< id<< '\\\
';
}

然后它说:

  void go(){
std :: unique_lock< std :: mutex> lck(mtx);
ready = true;
cv.notify_all();
}

现在我明白了,这两个函数都会停止 std :: unqique_lock 行。直到获得唯一的锁。也就是说,没有其他线程有锁。



因此,首先执行 print_id 函数。



如果 go 函数被调用,则该函数将在等待线上停止。执行(在单独的线程上),那里的代码将在唯一的锁定线上停止。因为互斥锁被 print_id 函数锁定。



显然,如果代码是这样,这将不起作用。但我真的没有看到我不在这里。

解决方案

缺少的是 wait 解锁互斥体,然后等待 cv 上的信号。



在返回前再次锁定互斥体。 / p>

您可以通过点击在您找到示例的页面上:


On my neverending quest to understand std::contion_variables I've run into the following. On this page it says the following:

void print_id (int id) {
  std::unique_lock<std::mutex> lck(mtx);
  while (!ready) cv.wait(lck);
  // ...
  std::cout << "thread " << id << '\n';
}

And after that it says this:

void go() {
  std::unique_lock<std::mutex> lck(mtx);
  ready = true;
  cv.notify_all();
}

Now as I understand it, both of these functions will halt on the std::unqique_lock line. Until a unique lock is acquired. That is, no other thread has a lock.

So say the print_id function is executed first. The unique lock will be aquired and the function will halt on the wait line.

If the go function is then executed (on a separate thread), the code there will halt on the unique lock line. Since the mutex is locked by the print_id function already.

Obviously this wouldn't work if the code was like that. But I really don't see what I'm not getting here. So please enlighten me.

解决方案

What you're missing is that wait unlocks the mutex and then waits for the signal on cv.

It locks the mutex again before returning.

You could have found this out by clicking on wait on the page where you found the example:

这篇关于为什么std :: condition_variable的notify和wait函数都需要一个锁定的互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:38