LinuxEvent.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef LINUX_EVENT_H
  2. #define LINUX_EVENT_H
  3. #include <atomic>
  4. #include <mutex>
  5. #include <memory>
  6. #include <unordered_map>
  7. #include <string>
  8. #include <functional>
  9. #include <chrono>
  10. #include <iostream>
  11. #include <iomanip>
  12. #include <sstream>
  13. #include <sys/eventfd.h>
  14. #include <unistd.h>
  15. #include <cstring>
  16. #include <poll.h>
  17. //// 辅助函数:生成带时间戳的日志前缀
  18. //inline std::string getLogPrefix() {
  19. // auto now = std::chrono::system_clock::now();
  20. // std::time_t time = std::chrono::system_clock::to_time_t(now);
  21. // char timeStr[26];
  22. // ctime_r(&time, timeStr);
  23. // timeStr[24] = '\0'; // 移除换行符
  24. // return "[" + std::string(timeStr) + "] [WARNING] ";
  25. //}
  26. class LinuxEvent : public std::enable_shared_from_this<LinuxEvent> {
  27. public:
  28. enum EventType {
  29. AUTO_RESET,
  30. MANUAL_RESET
  31. };
  32. explicit LinuxEvent(EventType type = MANUAL_RESET);
  33. ~LinuxEvent();
  34. // 禁止拷贝和赋值
  35. LinuxEvent(const LinuxEvent&) = delete;
  36. LinuxEvent& operator=(const LinuxEvent&) = delete;
  37. void SetEvent();
  38. void ResetEvent();
  39. bool IsSet() const;
  40. int GetFD() const;
  41. bool Wait(unsigned long timeoutMs = (unsigned long)-1);
  42. static int WaitForMultipleEvents(LinuxEvent** events, int count, unsigned long timeoutMs);
  43. static int WaitForMultipleEvents(std::vector<std::shared_ptr<LinuxEvent>>& events, unsigned long timeoutMs);
  44. // 跨进程支持
  45. static std::shared_ptr<LinuxEvent> OpenEvent(const char* name, bool inheritHandle = false);
  46. static std::shared_ptr<LinuxEvent> CreateEvent(EventType type, bool initialState, const char* name ="");
  47. static void CleanupNamedEvents();
  48. // 获取生命周期跟踪ID
  49. uint64_t getObjectId() const { return m_objectId; }
  50. private:
  51. std::string getCurrentTimestamp() const;
  52. std::string getLogPrefix() const;
  53. void Initialize(bool initialState);
  54. mutable std::mutex m_mutex;
  55. int m_fd;
  56. EventType m_type;
  57. std::atomic<bool> m_state;
  58. std::string m_name; // 用于命名事件
  59. const uint64_t m_objectId;
  60. std::atomic<bool> m_destructing{ false };
  61. // 用于命名事件管理的静态成员
  62. static std::mutex s_namedEventsMutex;
  63. static std::unordered_map<std::string, std::weak_ptr<LinuxEvent>> s_namedEvents;
  64. static std::atomic<uint64_t> s_objectCounter;
  65. };
  66. #endif // LINUX_EVENT_H