You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.5 KiB

  1. //
  2. // Created by zhaohe on 19-5-21.
  3. //
  4. #pragma once
  5. #include <atomic>
  6. #include <fstream>
  7. #include <iostream>
  8. #include <list>
  9. #include <map>
  10. #include <memory>
  11. #include <mutex>
  12. #include <set>
  13. #include <sstream>
  14. #include <string>
  15. #include <thread>
  16. #include <vector>
  17. //
  18. #include "iflytopcpp/core/basic/signal/signal.hpp"
  19. #include "iflytopcpp/core/spdlogfactory/logger.hpp"
  20. #include "iflytopcpp/core/zexception/zexception.hpp"
  21. namespace iflytop {
  22. namespace core {
  23. using namespace std;
  24. class Thread;
  25. class Thread {
  26. ENABLE_LOGGER(Thread);
  27. public:
  28. private:
  29. string name;
  30. pthread_t id = 0;
  31. function<void()> run;
  32. std::mutex lock_;
  33. unique_ptr<std::thread> workThread;
  34. atomic_bool hasJointd = {false};
  35. atomic_bool exitFlag = {false};
  36. bool waitingForJoin = false; /*当前线程是否运行退出等待回收*/
  37. Singal signal;
  38. Thread(std::function<void()> run);
  39. public:
  40. Thread(string name, function<void()> run);
  41. void wake();
  42. void join();
  43. bool isWaitingForJoin() { return waitingForJoin; }
  44. bool getExitFlag() { return exitFlag; }
  45. pthread_t getId() const;
  46. void sleep() { signal.sleep(); }
  47. void sleepForMs(int64_t ms) { signal.sleep_for_us(ms * 1000); }
  48. ~Thread();
  49. private:
  50. const shared_ptr<zexception> &getExitException() const;
  51. };
  52. class ThisThread {
  53. Thread *m_thread = NULL;
  54. public:
  55. ThisThread();
  56. pthread_t getId() const { return pthread_self(); }
  57. bool getExitFlag();
  58. void sleep();
  59. void sleepForMs(int64_t ms);
  60. void wake();
  61. };
  62. } // namespace core
  63. } // namespace iflytop