簡體   English   中英

終止以無限循環運行的std :: thread

[英]Terminating an std::thread which runs in endless loop

我如何在Bar的析構函數中終止我分離出的線程(而不必等到線程從其睡眠中醒來)?

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;

};

您可以使用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_;
};

這應該使您對可能的操作有一個整體的了解:

  • 您可以使用bool來控制循環(使用std::mutex使用受保護的讀寫訪問權限);
  • 您使用std::condition_variable喚醒線程,以避免等待LONG_PERIOD

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM