c++ - 终止在无限循环中运行的 std::thread

标签 c++ multithreading c++11

如何在 Bar 的析构函数中终止我的分离线程(而不必等到线程从 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;

};

最佳答案

你可以使用 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 进行 protected 读写访问);
  • 您使用 std::condition_variable 唤醒线程以避免等待 LONG_PERIOD

关于c++ - 终止在无限循环中运行的 std::thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40162902/

相关文章:

c++ - CMake链接器输入文件未使用,因为未完成链接

c++ - 为什么智能指针没有返回基指针的转换运算符?

multithreading - 有没有办法让 visual studio 中的多线程调试像 eclipse 一样工作?

c++ - 元组查找函数参数替换失败

c++ - 热处理 c++11 lambda,同时捕获此指针并指定调用约定

c++ - 具有线程支持和 Bcast 调用的 MPI

c++ - const_cast const STL 容器,它是未定义的行为吗?

java - 如何使状态变量线程安全

python - 为什么Python多处理管理器会产生线程锁?

c++ - 接受任何表示/周期的 std::chrono::duration