代码之家  ›  专栏  ›  技术社区  ›  intrigued_66

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

  •  1
  • intrigued_66  · 技术社区  · 7 年前

    我把一根线从班上拆下来 B :

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

    作为正常操作的一部分,它等待条件变量:

    cv.wait(lock);
    

    但是,当我关闭B应用程序时,分离的线程仍然存在在下列情况下如何停止/清理此线程 B::~B() 被叫来了?

    2 回复  |  直到 7 年前
        1
  •  2
  •   seccpur    7 年前

    尝试以下代码段:set bool member variable 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();
    
        2
  •  3
  •   Maxim Egorushkin    7 年前

    使另一个线程协同终止非分离线程使干净地终止变得更容易,这样就不会过早地破坏另一个线程访问的状态:

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