简体   繁体   中英

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

I have a std::thread waiting and reading from a socket. And there is a pointer to this thread stored somewhere. 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. (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. The thread can hold a shared_ptr to this control structure and use it to report its status to any other interested code. When nobody cares about this thread anymore, the last shared_ptr to this control structure will go away and it will be destroyed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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