使用条件变量condition_variable实现超时功能
#include <iostream>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <pthread.h>
#include <chrono>
using namespace std::chrono_literals;
std::condition_variable cv;
std::mutex cv_m;
std::atomic<int> i{0};
void signals()
{
std::this_thread::sleep_for(120ms);
std::cerr << "Notifying...\n";
cv.notify_all();
i = 100;
}
void func() {
std::thread t1(signals);
t1.detach();
std::unique_lock<std::mutex> lk(cv_m);
auto now = std::chrono::system_clock::now();
auto end = now + std::chrono::milliseconds(100); //结束时间
// auto end = now + std::chrono::milliseconds(200); //结束时间
if(cv.wait_until(lk, end, [](){return i == 100;})) {
std::cerr << "Thread " << 1 << " finished waiting. i == " << i << '\n';
return;
}
else{
std::cerr << "Thread " << 1 << " timed out. i == " << i << '\n';
return;
}
}
int main()
{
auto start = std::chrono::high_resolution_clock::now();
func();
auto stop = std::chrono::high_resolution_clock::now();
std::cout << "interval " << (stop - start).count() << std::endl;
return 0;
}