gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:00:09 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com