简体   繁体   中英

storage model for File_descriptor and Handle in Reactor pattern

I'm implementing the asynchronous pattern Reactor in C++, based on Epoll. First, we will register file descriptor with the Reactor by calling the function

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
}

And then, the method hand_events, which run forever, is called

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(...)
    }
}

My question how to organize the storage model in this situation: store Handle, and mapping between file descriptor and handle (is there any suitable Pattern for it)

Hope to see your answer!

If all handlers have the same signature, then using std::function in a std::unordered_map might be enough.

std::unordered_map<int, std::function<void(int)>> fdmap;

Then store like

fdmap[descriptor] = handle;

And simply call like

fdmap[event.data.fd](event.data.fd);

Of course, in event handler you want to make sure that the mapping actually contains the file descriptor.


You should be able to use different signatures if you use std::bind when calling your register function:

my_reactor.register(fd, std::bind(my_handler, _1, another_argument, a_third_argument));

Then when the event dispatcher calls your event handler function it would be the same as calling it with the first argument as the descriptor and the other arguments with the values you pass them in the std::bind call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM