user695652 user695652 - 1 month ago 10
C++ Question

Terminating an std::thread which runs in endless loop

How can I terminate my spun off thread in the destructor of Bar (without having to wait until the thread woke up form its sleep)?

class Bar {

public:

Bar() : thread(&Bar:foo, this) {
}

~Bar() { // terminate thread here}



...

void foo() {
while (true) {
std::this_thread::sleep_for(
std::chrono::seconds(LONG_PERIOD));

//do stuff//
}

}

private:
std::thread thread;

};

Answer

You could use a std::condition_variable:

class Bar {
public:   
    Bar() : t_(&Bar:foo, this) { }
    ~Bar() { 
        {
            std::unique_lock<std::mutex> lk(m_);
            keep_ = false;
            cv.notify_one();
        }
        t_.join();
    }

    void foo() {
        while (true) {
            std::unique_lock<std::mutex> lk(m_);
            if (!keep_) break;
            if (cv.wait_for(lk, LONG_PERIOD) == std::cv_status::no_timeout) {
                continue;
            }   
        }
    }

private:

    bool keep_{true};

    std::thread t_;
    std::mutex m_;
    std::condition_variable cv_;
};

This should give you a global idea of what you may do:

  • You use an std::atomic<bool> to control the loop;
  • You use an std::condition_variable to wake up the thread to avoid waiting LONG_PERIOD.