不同点:
- pthread_cond_timedwait需要在调用前自己调用mtx.lock();
- condition_variable.wait_for调用前unique_lock
lck(mtx);加锁的事wait_for里面实现了。
共同点:
- 运行时会mtx.unlock(),检查条件时,mtx.lock(),检查完之后mtx.unlock;
- 超时或被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状态的。