Boost.Asio是个非常易用的C++异步网络库,官方文档中一个示例是聊天服务,分为chat_message、chat_client、chat_server三个部分。chat_server的启动代码如下。
if (argc < )
{
std::cerr << "Usage: chat_server <port> [<port> ...]\n";
return ;
} boost::asio::io_service io_service; chat_server_list servers;
for (int i = ; i < argc; ++i)
{
using namespace std; // For atoi.
tcp::endpoint endpoint(tcp::v4(), atoi(argv[i]));
chat_server_ptr server(new chat_server(io_service, endpoint));
servers.push_back(server);
} io_service.run();
从中可以看出,输入多个端口号会启动多个chat_server,但只有一个io_service,也就是说多个chat_server中产生的异步任务handler被放入同一个任务队列(由唯一的io_service维护),这就相当于用一个线程同时处理多个聊天服务器,自然会对系统的性能产生影响。
从io_service_pool这个示例中可以得到一点改进的启发,每个chat_server绑定一个io_service,每个io_service在一个独立的线程中运行,这样就能充分利用机器的多核性能,改进代码如下。
if (argc < )
{
std::cerr << "Usage: chat_server <port> [<port> ...]\n";
return ;
} typedef boost::shared_ptr<boost::asio::io_service> io_service_ptr;
typedef std::list<io_service_ptr> io_service_list; chat_server_list servers;
io_service_list services;
for (int i = ; i < argc; ++i)
{
using namespace std; // For atoi.
tcp::endpoint endpoint(tcp::v4(), atoi(argv[i]));
io_service_ptr service(new boost::asio::io_service);
chat_server_ptr server(new chat_server(*service, endpoint));
services.push_back(service);
servers.push_back(server);
} std::vector<std::shared_ptr<std::thread> > threads;
for(auto service : services)
{
auto run_func = [](const io_service_ptr& ptr) {
return ptr->run();
};
std::function<std::size_t()> f = std::bind(run_func, service);
std::shared_ptr<std::thread> thread(new std::thread(f));
threads.push_back(thread);
} // Wait for all threads in the pool to exit.
for (std::size_t i = ; i < threads.size(); ++i) {
threads[i]->join();
}