How do I sleep and wait with timeouts?

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;
}
        

C++ sleep timeout thread std::this_thread condition variable