简体   繁体   English

如何“停止”正在等待条件变量的分离线程?

[英]How to “stop” detached thread which is waiting on a condition variable?

I detach a thread from Class B : 我从B类分离线程:

t1 = std::thread(&Class::method, this);
t1.detach();

which as part of it's normal operation waits on a condition variable: 作为正常操作的一部分,它会等待条件变量:

cv.wait(lock);

However, when I close my B application the detached thread remains. 但是,当我关闭B应用程序时,分离的线程仍然存在。 How do I stop/clean-up this thread when B::~B() is called? 调用B::~B()时如何停止/清理该线程?

Try this snippet: Set bool member variable discard_ to true to avoid execution of your scheduled process execution: 尝试以下代码段:将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();

Make the other thread cooperate for termination. 使另一个线程配合终止。 Non-detached thread makes it easier to terminate cleanly, so that you do not destroy the state accessed by the other thread prematurely: 非分离线程使干净终止更容易,这样您就不会过早破坏其他线程访问的状态:

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.
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM