samedi 29 avril 2017

How to pass per-thread user data into asio handler?

I have a websocketpp-based (which as ASIO-based) server and a pool of threads. I need to allocate some resources (connection to DB and etc) and make sure they will be used exactly in the same thread always.

So, here is what I currently have:

class Server
    : public websocketpp::server<websocketpp::config::asio>
{
    Server();
    //...
    static void onMessage(Server * server,
                          websocketpp::connection_hdl hdl,
                          Server::message_ptr msg);
    //...
};

Server::Server()
{
    // ...some initialization routines.. //
    set_message_handler(
        std::bind(&onMessage,
                  this,
                  std::placeholders::_1,
                  std::placeholders::_2));
    listen(port);
    start_accept();
}

Somewhere at the main() function :

    Server server;

    // estimated thread pool
    std::vector<std::thread> threads;
    threads.reserve(threadsCount);
    for(int i = 0; i < threadsCount; ++i)
    {
        threads.emplace_back(
            [&server]()
            {
                mongo::Client mongo(config); // !HERE!
                server.run();
            });
    }

As you can see a mongo::Client instantiated at every thread. My goal is to pass ref/pointer to it (or any other resource that may be added in future) and receive it in Server::onMessage (as an additional parameter).

I'm completely out of ideas how to do this. Also, I don't want to create allocator interface like mongo::Client * Server::acquire() / Server::release(mongo::Client *), because it requires additional synchronization. My intention is to access (how?) to a some-kind of per-thread "userdata" within the Server::onMessage handler.

Aucun commentaire:

Enregistrer un commentaire