The correct way to kill threads waiting on std :: conditional_variable during main program exit

I use std :: conditional_variable to synchronize the signal in a multi-threaded program to control the flow of various critical sections. The program works, but during the exit I have to use the predicate (kill_ == true) to avoid destroying the threads that are still waiting on std :: conditional_variable :: wait (). I do not know if he correctly destroyed all the waiting threads, and asked for advice. Here's the code snippet:

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();
}
+4
source share
1 answer

, . , , ( , ..):

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

, timer::section() std::thread thread1.

. , , kill_ = true , .notify_all() ( , ).

, std:: unique_lock :

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

... .

+3

Source: https://habr.com/ru/post/1666685/


All Articles