简体   繁体   中英

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(eg 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 ?

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM