简体   繁体   中英

Boost asio not able to run io service on all threads., io service is blocking at first thread call

I am trying to create a multi-threaded server by following the example HTTP Server 3 . I have followed as shown in the example.

server code for creation of threads. version 1

for (std::size_t i = 0; i < thread_pool_size_; ++i) {
    boost::shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &ios_)));
    threads_.push_back(thread);
  }
  for (std::size_t i = 0; i < threads_.size(); ++i){
        LOGV << "performing join operation for thread = "<< i;
    threads_[i]->join();
  }

version 2

for (std::size_t i = 0; i < thread_pool_size_; ++i) {
  boost::shared_ptr<boost::thread> thread(new boost::thread(
    [this](){ LOGV << "Intiating thread"; this->ios_.run(); }));
    threads_.push_back(thread);
  }
  for (std::size_t i = 0; i < threads_.size(); ++i){
        LOGV << "performing join operation for thread = "<< i;
    threads_[i]->join();
  }

version 1 gives me output:

performing join operation for thread = 0

version 2 gives me the following output with 10 threads.

[Tcp::Server::run@76] Initiating threads Initiating thread
Initiating thread
Initiating thread
Initiating thread
Initiating thread
Initiating thread
Initiating thread
Initiating thread
performing join operation for thread = 0
Initiating thread
Initiating thread

I want to understand whether all threads are used, or only one thread that executed join operation is used. Can someone please explain where I went wrong and suggest if there is any good approach to do this, I am also using strand in the same way as example suggested.

Thanks in advance

I want to understand wether all threads are used, or only one thread that executed join operation is used..

The former. The join function will just block the until the to be joined thread has exited execution, but generally all threads will immediately start to run once they got handed over a routine (eg by constructor) they can execute, irrespective of any join or detach calls.

In context of asio of course only those threads can handle I/O that made a call to eg io_service::run .

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