c++11中的condition_variable和之前的pthread_cond_timedwait的不同之处


不同点:

  1. pthread_cond_timedwait需要在调用前自己调用mtx.lock();
  2. condition_variable.wait_for调用前unique_lock lck(mtx);加锁的事wait_for里面实现了。

共同点:

  1. 运行时会mtx.unlock(),检查条件时,mtx.lock(),检查完之后mtx.unlock;
  2. 超时或被signal后,跳出来,此时mtx处于lock的状态;

测试c++11特性

示例代码:

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <chrono>             // std::chrono::seconds
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable, std::cv_status

using namespace std;

std::condition_variable cv;
std::mutex mtx;

int value;

void read_value() {
  int cnt = 0;
  while (1) {
      this_thread::sleep_for(chrono::seconds(2));
      mtx.lock();
      cout << "sub thread." << endl;
      mtx.unlock();
      cnt++;
      if (cnt > 5) {
         cv.notify_one();
      }
  }
}

int main ()
{
  std::thread th (read_value);
  std::unique_lock<std::mutex> lck(mtx);
  //lck.lock(); 这里放开会报死锁
  while (cv.wait_for(lck,std::chrono::seconds(5))==std::cv_status::timeout) {
    //this_thread::sleep_for(chrono::seconds(3)); 
    std::cout << 'main thread.' << std::endl;
  }
  lck.unlock(); //这里注释掉之后sub thread会被一直锁住
  std::cout << "end. " << '\n';
  this_thread::sleep_for(chrono::seconds(2000));

  th.join();

  return 0;
}
//编译命令:g++ -g main.cpp -lpthread -o main -std=c++11

结果可以看到打印2次sub,会打印一次main, 说明wait_for在等待超时时mtx是处于unlock状态的。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM