Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 540
Farzam Avatar asked Oct 23 '25 19:10

Farzam


1 Answers

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;
}
like image 82
Clonk Avatar answered Oct 26 '25 08:10

Clonk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!