#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() ) {
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 operator()() {
for( unsigned j=0; j<1000000; ++j ) {
if( j%10000 == 0 ) {
std::cout << "In S::operator () j = " << j << "\n";
}
}
}
};
int main()
{
int some_local_state=0;
S obj( some_local_state );
std::thread t( obj ); // creating thread from operator() - simpler syntax
thread_guard g( t );
std::cout << "In main thread\n";
}