CppNoob
CppNoob

Reputation: 2390

Using the same Boost.Asio io_service for accepting tcp connections synchronously and as a thread pool

Is the following method of using io_service for accepting tcp connections and also as a thread pool for serving connected clients valid, or is there some caveat?

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 */ });
}

...

Upvotes: 1

Views: 244

Answers (1)

sehe
sehe

Reputation: 393064

That's perfectly fine.

A caveat would be if you post tasks that block for non-trivial amounts of time.

Async IO operations all imply very short execution times. If you clog the service threads with non-IO tasks, the IO tasks will get high(er) latency

Upvotes: 1

Related Questions