123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- #ifndef LINUX_EVENT_H
- #define LINUX_EVENT_H
- #include <atomic>
- #include <mutex>
- #include <memory>
- #include <unordered_map>
- #include <string>
- #include <functional>
- #include <chrono>
- #include <iostream>
- #include <iomanip>
- #include <sstream>
- #include <sys/eventfd.h>
- #include <unistd.h>
- #include <cstring>
- #include <poll.h>
- //// 辅助函数:生成带时间戳的日志前缀
- //inline std::string getLogPrefix() {
- // auto now = std::chrono::system_clock::now();
- // std::time_t time = std::chrono::system_clock::to_time_t(now);
- // char timeStr[26];
- // ctime_r(&time, timeStr);
- // timeStr[24] = '\0'; // 移除换行符
- // return "[" + std::string(timeStr) + "] [WARNING] ";
- //}
- class LinuxEvent : public std::enable_shared_from_this<LinuxEvent> {
- public:
- enum EventType {
- AUTO_RESET,
- MANUAL_RESET
- };
- explicit LinuxEvent(EventType type = MANUAL_RESET);
- ~LinuxEvent();
- // 禁止拷贝和赋值
- LinuxEvent(const LinuxEvent&) = delete;
- LinuxEvent& operator=(const LinuxEvent&) = delete;
-
- void SetEvent();
- void ResetEvent();
- bool IsSet() const;
- int GetFD() const;
- bool Wait(unsigned long timeoutMs = (unsigned long)-1);
- static int WaitForMultipleEvents(LinuxEvent** events, int count, unsigned long timeoutMs);
- static int WaitForMultipleEvents(std::vector<std::shared_ptr<LinuxEvent>>& events, unsigned long timeoutMs);
- // 跨进程支持
- static std::shared_ptr<LinuxEvent> OpenEvent(const char* name, bool inheritHandle = false);
- static std::shared_ptr<LinuxEvent> CreateEvent(EventType type, bool initialState, const char* name ="");
- static void CleanupNamedEvents();
- // 获取生命周期跟踪ID
- uint64_t getObjectId() const { return m_objectId; }
- private:
- std::string getCurrentTimestamp() const;
- std::string getLogPrefix() const;
- void Initialize(bool initialState);
- mutable std::mutex m_mutex;
- int m_fd;
- EventType m_type;
- std::atomic<bool> m_state;
- std::string m_name; // 用于命名事件
- const uint64_t m_objectId;
- std::atomic<bool> m_destructing{ false };
- // 用于命名事件管理的静态成员
- static std::mutex s_namedEventsMutex;
- static std::unordered_map<std::string, std::weak_ptr<LinuxEvent>> s_namedEvents;
- static std::atomic<uint64_t> s_objectCounter;
- };
- #endif // LINUX_EVENT_H
|