我正在基于 Epoll 使用 C++ 实现异步模式 Reactor。 首先,我们将通过调用函数向 Reactor 注册文件描述符
template<typename Handle>
void Reactor::register(int descriptor, Handle handle){
//add this descriptor to epoll for monitoring
//store this handle with the key is the descriptor
}
然后,调用永远运行的 hand_events 方法
void Reactor::handle_events(){
epoll_wait(..)
for(event in events){
//call the handle corresponding to the file descriptor return from epoll
//event.data.fd ==> handle
handle(...)
}
}
我的问题是在这种情况下如何组织存储模型:存储句柄,以及文件描述符和句柄之间的映射(是否有合适的模式)
希望看到你的回答!
最佳答案
如果所有处理程序都具有相同的签名,则使用 std::function
在std::unordered_map
可能就足够了。
std::unordered_map<int, std::function<void(int)>> fdmap;
然后收藏
fdmap[descriptor] = handle;
然后简单地像这样调用
fdmap[event.data.fd](event.data.fd);
当然,在事件处理程序中,您要确保映射实际包含文件描述符。
如果您使用 std::bind
,您应该能够使用不同的签名调用注册函数时:
my_reactor.register(fd, std::bind(my_handler, _1, another_argument, a_third_argument));
然后,当事件调度程序调用您的事件处理函数时,这与使用第一个参数作为描述符并使用您在 std::bind
中传递给它们的值调用它的其他参数相同> 打电话。
关于c++ - Reactor 模式中 File_descriptor 和 Handle 的存储模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493660/