简体   繁体   English

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

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

I have a std::thread waiting and reading from a socket. 我有一个std::thread等待和从套接字读取。 And there is a pointer to this thread stored somewhere. 并且有一个指向该thread的指针存储在某个地方。 But when something bad happens and the thread ends, I want it to call something that results in a function that will join this thread and then delete the pointer referring to it. 但是,当发生不好的情况并且thread结束时,我希望它调用导致结果的函数,该函数将加入该线程,然后删除引用该线程的指针。 (I have access to that pointer from within the thread) (我可以从线程内访问该指针)

I could do that in another thread but then that new thread becomes the problem. 我可以在另一个线程中执行此操作,但是那个新线程就成了问题。

Change your design so that you don't have this bizarre requirement. 更改您的设计,以便您没有这种奇怪的要求。 One simple solution is to use shared_ptr s to a control structure that owns the thread and has other status information as well. 一个简单的解决方案是对一个拥有线程并具有其他状态信息的控制结构使用shared_ptr The thread can hold a shared_ptr to this control structure and use it to report its status to any other interested code. 线程可以将shared_ptr保留到此控件结构,并使用它向其他任何感兴趣的代码报告其状态。 When nobody cares about this thread anymore, the last shared_ptr to this control structure will go away and it will be destroyed. 当没有人关心这个线程时,此控制结构的最后一个shared_ptr将消失并被销毁。

You could create your thread in a detached state, and make your thread lifetime dependent a condition variable and switch a boolean state on finish. 您可以在分离状态下创建线程,并使线程生存期与条件变量相关,并在完成时切换布尔状态。

#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