In C++, sleeping and waiting with timeouts can be effectively managed using features from the standard library, such as std::this_thread::sleep_for
and condition variables to implement wait logic. Below is an example demonstrating how to use these features.
This example illustrates how to pause execution of a thread for a specified duration and how to implement a wait with a timeout.
C++, sleep, timeout, thread, std::this_thread, condition variable
#include <iostream>
#include <thread>
#include <chrono>
#include <condition_variable>
std::condition_variable cv;
std::mutex mtx;
bool ready = false;
void work() {
std::this_thread::sleep_for(std::chrono::seconds(2)); // Simulate work
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
}
int main() {
std::thread t(work);
// Wait for work to finish with a timeout of 3 seconds
{
std::unique_lock<std::mutex> lock(mtx);
if (cv.wait_for(lock, std::chrono::seconds(3), [] { return ready; })) {
std::cout << "Work finished." << std::endl;
} else {
std::cout << "Timeout occurred!" << std::endl;
}
}
t.join();
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?