Skip to content

Instantly share code, notes, and snippets.

@fernandoc1
Last active September 19, 2019 19:43
Show Gist options
  • Save fernandoc1/093c206d3ac8d943fc1a8791ac75f34f to your computer and use it in GitHub Desktop.
Save fernandoc1/093c206d3ac8d943fc1a8791ac75f34f to your computer and use it in GitHub Desktop.
This is a timer thread example with a lambda function and std::condition_variable.
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <unistd.h>
int main(int argc, char** argv)
{
std::mutex m;
std::condition_variable condition;
bool operationReady = false;
std::thread timeoutThread([&]()
{
std::unique_lock<std::mutex> lock(m);
condition.wait_for(lock, std::chrono::seconds(1));
if(!operationReady)
{
std::cout << "Operation timed out. Quitting..." << std::endl;
exit(1);
}
});
std::cout << "Sleeping" << std::endl;
sleep(2);
operationReady = true;
condition.notify_all();
std::cout << "Operation ready" << std::endl;
timeoutThread.join();
return 0;
}
@fernandoc1
Copy link
Author

To compile this:

g++ timer_example.cpp -std=c++11 -lpthread

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment