不同點:
- 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狀態的。
