【问题标题】:How to pass per-thread user data into asio handler?如何将每个线程的用户数据传递到 asio 处理程序?
【发布时间】:2017-04-29 12:45:35
【问题描述】:

我有一个基于 websocketpp(基于 ASIO)的服务器和一个线程池。我需要分配一些资源(连接到 DB 等)并确保它们始终在同一个线程中完全使用。

所以,这是我目前拥有的:

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

main() 函数的某处:

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

正如您所见,mongo::Client 在每个线程中都被实例化了。我的目标是将引用/指针传递给它(或将来可能添加的任何其他资源)并在Server::onMessage 中接收它(作为附加参数)。

我完全不知道如何做到这一点。另外,我不想创建像mongo::Client * Server::acquire() / Server::release(mongo::Client *) 这样的分配器接口,因为它需要额外的同步。我的意图是访问(如何?)Server::onMessage 处理程序中的某种每线程“用户数据”。

【问题讨论】:

    标签: c++ c++11 c++14 boost-asio websocket++


    【解决方案1】:

    线程本地存储可能会起作用。

    例如,使用struct 来保存您的 mongo 客户端:

    struct ThreadData
    {
        mongo::Client client;
    }
    

    然后,声明一个线程本地的ThreadData 对象:

    thread_local ThreadData data;
    
    int main( int argc, char* argv[] )
    {
        Server server;
    
        // estimated thread pool
        std::vector<std::thread> threads;
        threads.reserve(threadsCount);
        for(int i = 0; i < threadsCount; ++i)
        {
            threads.emplace_back(
                [&server]()
                {
                    // 'data' is thread-local
                    data.client = mongo::Client(config);
                    server.run();
                });
        }
    }
    

    每个线程都是data 的线程本地副本,因此您可以在Server::onMessage(...) 中访问它而无需进一步同步。

    【讨论】:

      【解决方案2】:

      您可能想看看 WebSocket++ 的 broadcast_server example。这是一个基本广播器的实现,它维护着一个活动连接列表,其中一个连接发送的任何消息都会发送到所有连接。

      该示例使用两个线程。主线程处理服务器事件,将它们转换为添加到队列中的“动作”。工作线程(通过thread t(bind(&amp;broadcast_server::process_messages,&amp;server_instance)) 创建)处理队列中的操作。

      您可以创建多个工作线程,每个工作线程都有自己的 mongo::Client 和任何其他资源,从队列中获取接收到的消息并进行处理。

      【讨论】:

      • 我认为非常好的解决方案。 aaron 的 thread_local 方法看起来也不错,但成本很低,而且语义可能更复杂。现在我不确定哪个更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 2013-08-14
      • 2015-10-08
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      相关资源
      最近更新 更多