mardi 2 octobre 2018

How to wake an std::thread while it is sleeping

I am using C++ 11 and I have an std::thread which is a class member and it sends a necessary info piece to listeners in every 2 minutes. Other that that it just sleeps. So, I have made it to sleep for 2 minutes and then send the required info and then sleep for 2 minutes again.

// MyClass.hpp
MyClass {

    ~MyClass();
    RunMyThread();

private:
    std::thread my_thread;
    std::atomic<bool> m_running;
}


MyClass::RunMyThread() {

    my_thread = std::thread { [this, m_running] {
    m_running = true;
    while(m_running) {
        std::this_thread::sleep_for(std::chrono::minutes(2));
        SendStatusInfo(some_info);
    }
}};
}

~MyClass::MyClass() {
    m_running = false; // this wont work as the thread is sleeping. How to exit thread here?
}

Issue:
The issue with this approach is that I cannot exit the thread while it is sleeping. I understand that I can wake it and exit using a std::condition_variable technique? But I am struggling to find a simple example which does simplistically as in above scenario.

Question:
How can I use an std::condition_variable to wake the thread and exit gracefully while it was sleeping? Or are there any other ways of achieving the same?

Additionally, I see that I need to use a std::mutex in conjunction with std::condition_variable? Is that really necessary? Is it not possible to achieve the goal by adding the std::condition_variable logic only to required places in the code piece here?

Aucun commentaire:

Enregistrer un commentaire