Search code examples
c++multithreadingdestructor

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?


Solution

  • 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.