asit_dhal
asit_dhal

Reputation: 1269

boost asio io_service object and the underlying threads

I am using boost asio library. This is my implementation

boost::asio::io_service ioservice;
boost::asio::io_service::work work(ioservice);
boost::thread_group threads;
for (int i = 0; i < 10; i++)
{
    threads.create_thread(
      boost::bind(&boost::asio::io_service::run, &ioservice));
}

Then I pass this instance of ioservice object as an argument whenever I need an io service object(e.g asynchronous read/write/timer). If i need to deal with a lot of async operation, I just increase the no of threads.

Some of colleagues create multiple io service object with only one worker thread.

Which one is the correct implementation ? Can it be improved ?

Upvotes: 1

Views: 529

Answers (1)

Collin Dauphinee
Collin Dauphinee

Reputation: 13973

Both approaches are correct, but it depends on what you're trying to accomplish. An io_service makes a great cross-platform thread-safe work queue.

If you want some work to be processed on a certain thread (i.e. to serialize certain work items), it makes sense to have one io_service being run on one thread.

If you want some work to be processed, but don't care about which thread it's processed on or the order, it makes sense to have one io_service being run on multiple threads.

Upvotes: 2

Related Questions