c++ - 在主程序退出期间销毁等待 std::condition_variable 的线程的正确方法

标签 c++ multithreading condition-variable

我正在使用 std::conditional_variable 为多线程程序中的信号计时,以控制各个关键部分的流程。该程序可以运行,但在退出期间我不得不使用谓词 (kill_ == true) 来避免破坏仍在等待 std::conditional_variable::wait() 的线程。我不知道它是否是销毁所有等待线程的正确方法,征求意见。这是一个代码片段:

class timer
{
  // ...
       timer(std::shared_ptr<parent_object> parent,const bool& kill)
         :parent_(parent),kill_(kill){}

  private:
       std::condition_variable cv_command_flow_;
       std::mutex mu_flow_;
       const bool& kill_;
       std::shared_ptr<parent_object> parent_;
};

void timer::section()
{
       auto delay = get_next_delay();

       std::unique_lock<std::mutex> lock(mu_flow_);
       std::cv_command_flow_.wait_until(lock,delay,[] { return kill_ == true; });

       if( kill_) return;

       parent_->trigger();

       std::cv_command_exec_.notify_all();
}

最佳答案

这通常是我处理等待线程销毁的方式。您将需要一个这样的代码段来执行清理(在类析构函数中、进程退出前的主线程等):

{
  std::lock_guard<std::mutex> lock(mu_flow);
  kill_ = true;
}
cv_command_exec_.notify_all();
thread1.join();

我假设 timer::section() 在某个线程 std::thread thread1 中执行。

互斥量的所有权持续时间由作用域 block 控制。您只希望在设置 kill_ = true 并在调用 .notify_all() 之前释放互斥锁(否则被唤醒的线程可能会发现锁仍然持有并继续回去 sleep )。

当然,std::unique_lock 的用法如下:

std::unique_lock<std::mutex> lock(mu_flow);
kill_ = true;
lock.unlock();
cv_command_exec_.notify_all();
thread1.join();

这在很大程度上是个人偏好......两个代码部分完成相同的任务。

关于c++ - 在主程序退出期间销毁等待 std::condition_variable 的线程的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41627918/

相关文章:

java - ConditionVariable 防止两个线程同时运行

c++ - std::condition_variable::notify_one 是可重入的吗?

C++14/1y : Standard ref for "operator+ must take either one or two arguments"?

multithreading - Threads.数组中的最大值

java - 在另一个线程完成执行后执行某些操作

c - 如何通过pthread管理两个或更多的使用者?

c - 如果我们需要按特定顺序打印多线程计算的结果,为什么信号而不是广播有效?

c++ - googletest 字符串化可以产生十六进制格式吗?

c++ - 联盟初始化

c++ - C++中如何在没有WMI的情况下获取硬件信息?