#include <iostream>
#include <thread>

//RAII
class thread_guard {
        std::thread& t;
    public:

        explicit thread_guard( std::thread& t_ ): t( t_ ) {}

        ~thread_guard() {
            if( t.joinable() ) { // unless someone already joined this thread
                t.join();
            }
        }

        thread_guard( thread_guard const& )=delete;
        thread_guard& operator=( thread_guard const& )=delete;
};

struct S {
    int& i;

    S( int& i_ ):i( i_ ) {}

    void dowork1() {
        for( unsigned j=0; j<1000000; ++j ) {
            if( j%10000 == 0 ) {
                std::cout << "In S::dowork1 () j = " << j << "\n";
            }
        }
    }
    void dowork2() {
        for( unsigned j=0; j<1000000; ++j ) {
            if( j%10000 == 0 ) {
                std::cout << "In S::dowork2 () j = " << j << "\n";
            }
        }
    }
};


int main()
{
    int some_local_state=0;
    S obj( some_local_state );
    std::thread t( &S::dowork1, &obj );
    std::thread t2( &S::dowork2, &obj );
    thread_guard g1( t );
    thread_guard g2( t2 );
    t2.join();
    std::cout << "In main thread\n";
}