繁体   English   中英

如何从自身加入std :: thread(在C ++ 11中)

[英]How to join a std::thread from itself (in C++11)

我有一个std::thread等待和从套接字读取。 并且有一个指向该thread的指针存储在某个地方。 但是,当发生不好的情况并且thread结束时,我希望它调用导致结果的函数,该函数将加入该线程,然后删除引用该线程的指针。 (我可以从线程内访问该指针)

我可以在另一个线程中执行此操作,但是那个新线程就成了问题。

更改您的设计,以便您没有这种奇怪的要求。 一个简单的解决方案是对一个拥有线程并具有其他状态信息的控制结构使用shared_ptr 线程可以将shared_ptr保留到此控件结构,并使用它向其他任何感兴趣的代码报告其状态。 当没有人关心这个线程时,此控制结构的最后一个shared_ptr将消失并被销毁。

您可以在分离状态下创建线程,并使线程生存期与条件变量相关,并在完成时切换布尔状态。

#include <thread>
#include <iostream>
#include <unistd.h>
#include <condition_variable>
#include <mutex>

class A {
    private:
        void Threadfunction();
        volatile bool class_running;
        volatile bool thread_running;
        std::condition_variable cv;
        std::mutex mu;
    public:
        A();
        ~A();
        void Stop();
};
A::A(){
    class_running = true;
    thread_running = false;
    std::thread t(&A::Threadfunction,this);
    t.detach();
}
A::~A(){
    if(class_running) {this->Stop();}
}
void A::Stop() {
    std::unique_lock<std::mutex> lk(mu);
    class_running = false;
    while(thread_running) {
        cv.wait(lk);
    }
    std::cout << "Stop ended " << std::endl;
}
void A::Threadfunction(){
    thread_running = true;
    std::cout << "thread started " << std::endl;
    while(class_running){
        // Do something
    }
    thread_running = false;
    cv.notify_one();
    std::cout << "thread stopped " << std::endl;
}
int main(){
    A a1;
    A a2;
    sleep(1);
    std::cout << "a1.Stop() called " << std::endl;
    a1.Stop();
    sleep(1);
    std::cout << "a2.Stop() not called but a2 goes out of scope and destructor is called " << std::endl;
}

暂无
暂无

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

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