ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
``` #ifndef _LOOP_EPOLL_H_ #define _LOOP_EPOLL_H_ #include <sys/epoll.h> #include <iostream> #include <unistd.h> #include <map> #include <functional> #include <memory> #include <thread> class LoopEpoll { public: typedef std::shared_ptr<LoopEpoll> ptr; typedef std::function<void()> Func; LoopEpoll() : stop_(false) { epfd_ = epoll_create(10); if (epfd_ < 0) { std::cout << "Failed to create epoll" << std::endl; exit(1); } } ~LoopEpoll() { close(epfd_); } void stop() { stop_ = true; } void updateEvent(int fd, int events, Func func) { auto it = events_.find(fd); if (it == events_.end()) { epoll_event e; e.data.fd = fd; e.events = events; events_[fd] = e; callbacks_[fd] = func; if (epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &e) < 0) { std::cout << "failed to add handler to epoll" << std::endl; } } else { epoll_event &e = events_[fd]; e.events = events; callbacks_[fd] = func; if (epoll_ctl(epfd_, EPOLL_CTL_MOD, fd, &e) < 0) { std::cout << "failed to modify handler to epoll" << std::endl; } } } void removeEvent(int fd) { auto it = events_.find(fd); if (it != events_.end()) { events_.erase(fd); callbacks_.erase(fd); if (epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, NULL) < 0) { std::cout << "failed to delete handler from epoll" << std::endl; } } } void run() { std::thread t(std::bind(loopEpoll, this, 1000)); t.detach(); } private: void loopEpoll(int timeout) { const uint64_t MAX_EVENTS = 1024; epoll_event events[MAX_EVENTS]; while (!stop_) { int nfds = epoll_wait(epfd_, events, MAX_EVENTS, timeout); for (int i = 0; i < nfds; ++i) { int active_fd = events[i].data.fd; removeEvent(active_fd); std::cout << "epoll_wait active_fd=" << active_fd << std::endl; Func cb = callbacks_[active_fd]; cb(); } } } private: int epfd_; bool stop_; std::map<int, epoll_event> events_; std::map<int, Func> callbacks_; }; #endif ``` ``` #ifndef _TIMER_H_ #define _TIMER_H_ #include <sys/timerfd.h> #include <iostream> #include <unistd.h> #include <map> #include <functional> #include <atomic> #include "loop_epoll.h" std::atomic<int> g_sequence_creator; class Timer { public: typedef std::function<void()> Func; Timer(LoopEpoll::ptr loopEpoll) : loopEpoll_(loopEpoll) { int timer_fd_ = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); if (timer_fd_ < 0) { std::cout << "timerfd_create faild!" << std::endl; } } ~Timer() { ::close(timer_fd_); } int runOnce(uint64_t when, Func cb) { } int runEvery(uint64_t when, Func cb, int interval) { } private: std::multimap<uint64_t, Func> callbacks_; int timer_fd_; LoopEpoll::ptr loopEpoll_; }; #endif ```