如何"stop"正在等待条件变量的分离线程?
How to "stop" detached thread which is waiting on a condition variable?
我从类B
:分离线程
t1 = std::thread(&Class::method, this);
t1.detach();
作为正常操作的一部分,它等待一个条件变量:
cv.wait(lock);
但是,当我关闭B应用程序时,分离的线程仍然存在。调用B::~B()
时,如何停止/清理此线程?
试试这个片段:将bool成员变量discard_
设置为true
,以避免执行计划的进程执行:
std::thread([&](){
std::lock_guard<std::mutex> lock(mutex_);
cv.wait(lock,[](){ return normal_predicate_here || discard_ ;});
if(discard_) return;
// execute scheduled process
}).detach();
让其他线程协同终止。非分离线程使干净地终止更容易,这样就不会过早地破坏其他线程访问的状态:
struct OtherThread {
std::mutex m_;
std::condition_variable c_;
bool stop_ = false;
std::thread t_;
void thread_function() {
for(;;) {
std::unique_lock<std::mutex> l(m_);
while(!stop_ /* || a-message-received */)
c_.wait(l);
if(stop_)
return;
// Process a message.
// ...
// Continue waiting for messages or stop.
}
}
~OtherThread() {
this->stop();
}
void stop() {
{
std::unique_lock<std::mutex> l(m_);
if(stop_)
return;
stop_ = true;
}
c_.notify_one();
t_.join(); // Wait till the thread exited, so that this object can be destroyed.
}
};
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- C++:如何读取分离变量,然后读取向量
- 如何"stop"正在等待条件变量的分离线程?
- GCC shared_ptr和地图上make_shared分离的变量类型错误
- POSIX 线程 - 使用条件变量 MEMORY LEAK 同步分离的线程
- c++将输入分离到不同的变量中
- 文件变得非常大,需要将数据分离到另一个文件中,但也需要使用私有变量.我怎样才能正确地做到这一点
- 从RSA密钥对变量中分离公钥和私钥
- 如何在同一个资源中分离String和Integer变量