[Solved] Using C++ how can I stop a sleep() thread? [closed]


You can end a sleep early by waiting on a condition variable and then signalling that condition variable when the mouse button is clicked.

Here is some proof-of-concept code which should show you how to do it:

#include <chrono>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <iostream>

using namespace std::chrono_literals;

std::chrono::time_point <std::chrono::steady_clock> start_time;
std::condition_variable cv;
std::mutex cv_m;

void demo_thread ()
{
    std::cout << "demo thread waiting...\n";
    std::unique_lock <std::mutex> lk (cv_m);
    cv.wait_for (lk, 1000ms);
    auto delta_t = std::chrono::steady_clock::now () - start_time;
    std::cout << "demo thread terminating, delta_t = " << std::chrono::duration_cast<std::chrono::milliseconds> (delta_t).count() << "ms\n";
}

int main ()
{
    start_time = std::chrono::steady_clock::now ();
    auto t = std::thread (demo_thread);
    std::cout << "main thread waiting...\n";
    std::this_thread::sleep_for (200ms);

    std::cout << "signal condition variable...\n";
    {
        std::unique_lock <std::mutex> lk (cv_m);
        cv.notify_one ();
    }
    t.join ();
    std::cout << "main thread terminating\n";
}

Output:

main thread waiting...
demo thread waiting...
signal condition variable...
demo thread terminating, delta_t = 200ms
main thread terminating

Live demo

solved Using C++ how can I stop a sleep() thread? [closed]