如何"stop"正在等待条件变量的分离线程?

How to "stop" detached thread which is waiting on a condition variable?

本文关键字:分离 变量 线程 条件 stop 在等待 如何      更新时间:2023-10-16

我从类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.
}
};