tinyrpc/includes/net/reactor.hpp

54 lines
1.3 KiB
C++

#pragma once
// #include "logger.hpp"
#include <functional>
#include <unordered_map>
#include <vector>
#include <cstdlib>
#include <sys/epoll.h>
#include <stdlib.h>
#include <mutex>
namespace tinyrpc {
class FdEvent;
class Reactor {
public:
using Task = std::function<void()>;
enum ReactorType {
Main = 1,
Sub = 2
};
public:
Reactor(ReactorType type = ReactorType::Main);
void loop();
void addFdEvent(FdEvent* fdEvent);
void delFdEvent(FdEvent* fdEvent);
void modFdEvent(FdEvent* fdEvent);
void stop();
void rouse();
void addTask(Task task, bool needRouse = false);
static Reactor* getReactor();
~Reactor();
// void addEvent()
private:
bool addFd(int fd, epoll_event ev);
bool delFd(int fd);
bool modFd(int fd, epoll_event ev);
void addRouseFd(int eventFd);
void processAllTasks();
private:
int m_epfd {-1};
int m_rousefd{-1};
int m_tid {-1}; // 所属线程的 id
bool m_is_stop {false};
bool m_is_looping {false};
ReactorType m_type {ReactorType::Main};
std::unordered_map<int, FdEvent*> m_listen_fd_events;
std::vector<Task> m_tasks;
std::mutex m_tasks_mtx;
};
}