以下使用 io_service 接受 tcp 连接并作为线程池为连接的客户端提供服务的方法是否有效,或者是否有一些注意事项?
io_service svc;
io_service::work work(svc);
// define the three threads in the io_service thread pool
thread t1( [&svc]() { svc.run(); } );
thread t2( [&svc]() { svc.run(); } );
thread t3( [&svc]() { svc.run(); } );
endpoint ep(ip::tcp::v4(), port);
acceptor acceptor(svc, ep);
while (true) {
shared_ptr<socket> sock(new socket(svc));
acceptor.accept(*sock);
// post a task to the io_service
svc.post( [sock]() { /* do stuff on sock here */ });
}
...
最佳答案
这很好。
请注意,如果您发布的任务会占用大量时间。
异步 IO 操作都意味着非常短的执行时间。如果您使用非 IO 任务阻塞服务线程,IO 任务将获得更高(呃)延迟
关于c++ - 使用相同的 Boost.Asio io_service 同步接受 tcp 连接并作为线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263913/