CThread.hpp 944 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef THREAD_H_
  2. #define THREAD_H_
  3. #include <thread>
  4. #include <iostream>
  5. #include <utility>
  6. #include <system_error>
  7. class CThread
  8. {
  9. public:
  10. CThread() : _bRun(false){}
  11. CThread(CThread& src): _bRun(src._bRun), _thread(move(src._thread)){src._bRun = false;}
  12. virtual ~CThread()
  13. {
  14. if(_thread.joinable())
  15. _thread.detach();
  16. }
  17. template <typename F, typename... Args>
  18. bool Start(F&& f, Args&&... args)
  19. {
  20. if(_bRun) return false;
  21. try
  22. {
  23. _bRun = true;
  24. _thread = std::thread(std::forward<F>(f), std::forward<Args>(args)...);
  25. }
  26. catch(std::system_error& ex)
  27. {
  28. std::cout << "start thread fails:" << ex.what() << std::endl;
  29. }
  30. catch(...)
  31. {
  32. std::cout << "start thread fails" << std::endl;
  33. }
  34. return _bRun;
  35. }
  36. bool IsRun() const {return _bRun;}
  37. void Join()
  38. {
  39. bool bRun = _bRun;
  40. _bRun = false;
  41. if(bRun)
  42. _thread.join();
  43. }
  44. private:
  45. bool _bRun;
  46. std::thread _thread;
  47. };
  48. #endif /* THREAD_H_ */