Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread joining using a destructor

This is a continuation to my question: Thread creation inside constructor

Now that I have successfully created a thread in a constructor, I know that it must be joined. As I am developing an API, I have no control over the main function so I can't join it there.

Will it be right to join the thread in the class destructor, considering that the instanced object of that class would have an application's lifetime?

like image 606
V Shreyas Avatar asked Jun 19 '15 06:06

V Shreyas


1 Answers

You could do that. However, are you really interested in the mechanism of launching a new thread, or are you perhaps interested in the effect of performing something asynchronously? If it's the latter, you can move to the higher level async mechanism:

#include <iostream>
#include <future>


void bar()
{
    std::cout << "I'm bar" << std::endl;
}

class foo
{
public:
    foo() :
        m_f(std::async(
            std::launch::async,
            bar))
    {

    }

    ~foo()
    {
        m_f.get();
    }

private:
    std::future<void> m_f;
};

int main ()
{
    foo f;
}
  • You're asking in the constructor to launch bar asynchronously. You don't care about managing the thread yourself - let the library handle that.

  • Place the resulting future in a member.

  • In the dtor, get the future.

like image 117
Ami Tavory Avatar answered Nov 02 '22 20:11

Ami Tavory