#include <unistd.h>
#include <iomanip>
#include <iostream>
#include <thread>
#include <utility>
class ManagedThread
{
public:
template< class Function, class... Args> explicit ManagedThread( Function&& f, Args&&... args);
~ManagedThread() { mThread.join(); }
bool isActive() const { return mActive; }
private:
volatile bool mActive;
std::thread mThread;
};
template< class Function, class... Args>
void threadFunction( volatile bool& active_flag, Function&& f, Args&&... args)
{
active_flag = true;
f( args...);
active_flag = false;
}
template< class Function, class... Args>
ManagedThread::ManagedThread( Function&& f, Args&&... args):
mActive( false),
mThread( threadFunction< Function, Args...>, std::ref( mActive),
std::ref( f), std::forward< Args>( args)...)
{
}
static void func() { std::cout << "thread 1" << std::endl; }
int main() {
ManagedThread mt1( func);
std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive() << std::endl;
::sleep( 1);
std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive() << std::endl;
return 0;
}
I2luY2x1ZGUgPHVuaXN0ZC5oPgojaW5jbHVkZSA8aW9tYW5pcD4KI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dGhyZWFkPgojaW5jbHVkZSA8dXRpbGl0eT4KCmNsYXNzIE1hbmFnZWRUaHJlYWQKewpwdWJsaWM6CiAgIHRlbXBsYXRlPCBjbGFzcyBGdW5jdGlvbiwgY2xhc3MuLi4gQXJncz4gZXhwbGljaXQgTWFuYWdlZFRocmVhZCggRnVuY3Rpb24mJiBmLCBBcmdzJiYuLi4gYXJncyk7CiAgIH5NYW5hZ2VkVGhyZWFkKCkgeyBtVGhyZWFkLmpvaW4oKTsgfQogICBib29sIGlzQWN0aXZlKCkgY29uc3QgeyByZXR1cm4gbUFjdGl2ZTsgfQpwcml2YXRlOgogICB2b2xhdGlsZSBib29sICBtQWN0aXZlOwogICBzdGQ6OnRocmVhZCAgICBtVGhyZWFkOwp9OwoKdGVtcGxhdGU8IGNsYXNzIEZ1bmN0aW9uLCBjbGFzcy4uLiBBcmdzPgogICB2b2lkIHRocmVhZEZ1bmN0aW9uKCB2b2xh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