【问题标题】:Simple multithreaded server in C++?C ++中的简单多线程服务器?
【发布时间】:2011-03-16 18:04:20
【问题描述】:

我想编写一个简单的服务器应用程序,它将从客户端应用程序获取命令并在单独的线程中运行这些命令。

我在看server class in dlib。有没有人有使用这个的经验?它与使用 Boost 的 Asio 相比如何?

【问题讨论】:

    标签: c++ sockets client-server


    【解决方案1】:

    一开始我会尝试不使用线程。我将从libevent 开始。你会发现libevent模型极其简单scales out way better than spawning a thread per request model。如果 libevent 无法处理您的用例,那么总会有 Erlang!

    【讨论】:

    • Boost.Asio 也非常适合这种单线程对多客户端类型的工作。
    【解决方案2】:

    异步 ​​I/O 在很多方面都比每个客户端线程模型更好。最佳性能实际上是通过每核线程实现的,每个线程执行异步 I/O。

    请注意,您的“多线程服务器”概念虽然并非完全错误,但与其他人使用该短语的含义完全不同。一般来说,它意味着每个连接一个线程,而不是对一个连接的响应跨线程并行化。

    您要求的示例只是单线程同步服务器+并行计算的组合。

    【讨论】:

      【解决方案3】:

      Boost Asio 很容易做到这一点。看看the examples in the Highscore tutorial,它展示了如何使用 Boost 进行多线程异步输入/输出。

      #include <boost/asio.hpp> 
      #include <boost/thread.hpp> 
      #include <iostream> 
      
      void handler1(const boost::system::error_code &ec) 
      { 
        std::cout << "5 s." << std::endl; 
      } 
      
      void handler2(const boost::system::error_code &ec) 
      { 
        std::cout << "5 s." << std::endl; 
      } 
      
      boost::asio::io_service io_service; 
      
      void run() 
      { 
        io_service.run(); 
      } 
      
      int main() 
      { 
        boost::asio::deadline_timer timer1(io_service, boost::posix_time::seconds(5)); 
        timer1.async_wait(handler1); 
        boost::asio::deadline_timer timer2(io_service, boost::posix_time::seconds(5)); 
        timer2.async_wait(handler2); 
        boost::thread thread1(run); 
        boost::thread thread2(run); 
        thread1.join(); 
        thread2.join(); 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-12
        • 1970-01-01
        • 2019-10-30
        • 2015-08-11
        • 2016-03-07
        • 2022-01-10
        • 1970-01-01
        • 2017-01-22
        相关资源
        最近更新 更多