heczaco
heczaco

Reputation: 318

Terminating running thread c++ std::thread

I want to run a thread that does something as simple as this:

main(){
    std::thread  thread_pulse([=]{
        *this->do_adress = true;
        std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
        *this->do_adress = false;
        //delete this thread to avoid memory leaks
    });
    //do some other stuff without waiting for the thread to terminate
}

how do I assure that when the thread execution is done the thread deleted and there are no memory leaks without waiting for the thread to finish execution on main?

EDIT:

thanks for the help, whith the help this worked as I wanted

main(){
    std::thread ([=]{
        *this->do_adress = true;
        std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
        *this->do_adress = false;
        //delete this thread to avoid memory leaks
    }).detach;
    //do some other stuff without waiting for the thread to terminate
}

Upvotes: 0

Views: 138

Answers (1)

NathanOliver
NathanOliver

Reputation: 180415

If you want to make sure the thread is done before you exit main then right before you return from main use

thread_pulse.join();

This will wait for thread_pulse to finish before continuing on.

If you do not care if the thread finishes then you can detach it like

thread_pulse.detach();

after you create it. This will let program end without an exception being thrown.


Alternatively you could build a wrapper class that stores the thread and when it gets destroyed it will call join or detach for you so you do not have to remember. You can use something like Scott Myers ThreadRAII

class ThreadRAII 
{     
public:     
    ThreadRAII(std::thread&& thread): t(std::move(thread)) {}
   ~ThreadRAII() { if (t.joinable()) t.join(); }
private:    
    std::thread t;    
};

And either modify to let you pick whether to join() or detach() or just hard code the behavior.

Upvotes: 4

Related Questions