简体   繁体   中英

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;

};

You could use a std::condition_variable :

class Bar {
public:   
    Bar() : t_(&Bar::foo, this) { }
    ~Bar() { 
        {
            // Lock mutex to avoid race condition (see Mark B comment).
            std::unique_lock<std::mutex> lk(m_);
            // Update keep_ and notify the thread.
            keep_ = false;
        } // Unlock the mutex (see std::unique_lock)
        cv_.notify_one();
        t_.join(); // Wait for the thread to finish
    }

    void foo() {
        std::unique_lock<std::mutex> lk(m_);
        while (keep_) {
            if (cv_.wait_for(lk, LONG_PERIOD) == std::cv_status::no_timeout) {
                continue; // On notify, just continue (keep_ is updated).
            }   
            // Do whatever the thread needs to do...
        }
    }

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 bool to control the loop (with protected read and write access using a std::mutex );
  • You use an std::condition_variable to wake up the thread to avoid waiting LONG_PERIOD .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM