Created
June 24, 2020 11:13
-
-
Save eao197/0dd8cf85b07a9e8e62ecbd31f4f915ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <chrono> | |
#include <condition_variable> | |
#include <iostream> | |
#include <mutex> | |
#include <thread> | |
using namespace std::chrono; | |
struct lock_context | |
{ | |
std::mutex m_lock; | |
std::condition_variable m_cv; | |
bool m_triggered{false}; | |
}; | |
void trigger_thread(lock_context & ctx) | |
{ | |
std::this_thread::sleep_for(seconds{1}); | |
std::lock_guard<std::mutex> lock{ctx.m_lock}; | |
ctx.m_triggered = true; | |
ctx.m_cv.notify_one(); | |
} | |
int main() | |
{ | |
lock_context ctx; | |
std::thread trigger{trigger_thread, std::ref(ctx)}; | |
{ | |
std::unique_lock<std::mutex> lock{ctx.m_lock}; | |
int multiplier = 1; | |
while(!ctx.m_triggered) | |
{ | |
const auto started_at = steady_clock::now(); | |
const auto wait_time = (steady_clock::time_point::max() - started_at) | |
- hours{24*multiplier}; | |
std::cout << "wait_time: " << duration_cast<milliseconds>( | |
wait_time).count() << "ms, days: " | |
<< multiplier << std::endl; | |
ctx.m_cv.wait_for(lock, wait_time, | |
[&ctx]{ return ctx.m_triggered; }); | |
const auto finished_at = steady_clock::now(); | |
std::cout << "wait for: " << duration_cast<milliseconds>( | |
finished_at - started_at).count() << "ms" << std::endl; | |
if(!ctx.m_triggered) | |
multiplier += 1000; | |
} | |
} | |
trigger.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment