fork(5) download
  1. #include <unistd.h>
  2. #include <iomanip>
  3. #include <iostream>
  4. #include <thread>
  5. #include <utility>
  6.  
  7. class ManagedThread
  8. {
  9. public:
  10. template< class Function, class... Args> explicit ManagedThread( Function&& f, Args&&... args);
  11. ~ManagedThread() { mThread.join(); }
  12. bool isActive() const { return mActive; }
  13. private:
  14. volatile bool mActive;
  15. std::thread mThread;
  16. };
  17.  
  18. template< class Function, class... Args>
  19. void threadFunction( volatile bool& active_flag, Function&& f, Args&&... args)
  20. {
  21. active_flag = true;
  22. f( args...);
  23. active_flag = false;
  24. }
  25.  
  26. template< class Function, class... Args>
  27. ManagedThread::ManagedThread( Function&& f, Args&&... args):
  28. mActive( false),
  29. mThread( threadFunction< Function, Args...>, std::ref( mActive),
  30. std::ref( f), std::forward< Args>( args)...)
  31. {
  32. }
  33.  
  34. static void func() { std::cout << "thread 1" << std::endl; }
  35.  
  36. int main() {
  37. ManagedThread mt1( func);
  38. std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive() << std::endl;
  39. ::sleep( 1);
  40. std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive() << std::endl;
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 5520KB
stdin
Standard input is empty
stdout
thread 1 active = false
thread 1
thread 1 active = false