< turn > Talking about the multithreading model of Boost.asio

Source: Internet
Author: User

This article transferred from: http://senlinzhan.github.io/2017/09/17/boost-asio/

Boost.asio There are two ways to support multithreading, the first is simpler: In a multithreaded scenario, each thread holds one io_service , and each thread calls its own io_service run() method.
Another way to support multithreading is to assign only one globally io_service , and let this io_service be shared among multiple threads, and each thread calls the global io_service run() method.

One I/O Service per thread

Let's first analyze the first scenario: in a multithreaded scenario, each thread holds one io_service (the usual practice is to keep the number of threads and CPU cores consistent). So what are the characteristics of this scheme?

    • On multicore machines, this scenario can take advantage of multiple CPU cores.
    • A socket descriptor is not shared among multiple threads, so there is no need to introduce a synchronization mechanism.
    • The blocking operation cannot be performed in the event handler, otherwise it will block the thread on which it is io_service located.

Here we implement one AsioIOServicePool , which encapsulates the creation of the thread pool [full code]:

classasioioservicepool{ Public:    usingIoservice =Boost::asio::io_service; usingWork =boost::asio::io_service::work; usingWorkptr = std::unique_ptr<work>; Asioioservicepool (std::size_t size=std::thread::hardware_concurrency ()): Ioservices_ (size), works_ (size), Nextioservice_ (0)    {         for(Std::size_t i =0; i < size; ++i) {Works_[i]= Std::unique_ptr<work> (NewWork (Ioservices_[i])); }         for(Std::size_t i =0; I < ioservices_.size (); ++i) {threads_.emplace_back ([ This, I]                                  () {ioservices_[i].run ();        }); }} asioioservicepool (ConstAsioioservicepool &) =Delete; Asioioservicepool&operator=(ConstAsioioservicepool &) =Delete; //returns a io_service using the Round-robin methodBoost::asio::io_service &Getioservice () {Auto&service = ioservices_[nextioservice_++]; if(Nextioservice_ = =ioservices_.size ()) {Nextioservice_=0; }        returnService; }    voidStop () { for(Auto &Work:works_)        {Work.reset (); }         for(Auto &T:threads_)        {T.join (); }    }Private: Std::vector<IOService>Ioservices_; Std::vector<WorkPtr>Works_; Std::vector<std::thread>Threads_; std::size_t Nextioservice_;};

AsioIOServicePoolIt's also easy to use:

Std::mutex MTX;             // Protect Std::cout Asioioservicepool pool; boost::asio::steady_timer timer{pool.getioservice (), std::chrono::seconds{2  }};timer.async_wait ([&MTX] (const Boost::system::error_code &EC)                  {                      std :: Lock_guardlock(MTX);                       "  " << Std::endl;                  }); Pool.stop ();
One I/O Service with multiple threads

Another scenario is to assign a global first io_service , then open multiple threads, and each thread calls this io_service run() method. This way, when an asynchronous event completes, the io_service corresponding event handler is handed over to any one thread to execute.
However, in the practical use of this scheme, some problems need to be noted:

    • Blocking operations (such as database query operations) are allowed in the event handler.
    • The number of threads can be greater than the number of CPU cores, for example, if you need to perform blocking operations in event handler, in order to increase the responsiveness of the program, you need to increase the number of threads.
    • Because multiple threads run the event loop at the same time, this can cause a problem: a socket descriptor may be shared among multiple threads, prone to race conditions (race condition). For example, if a socket's readable event occurs very quickly two times, then there will be two threads to read the same socket at the same time (can be used to strand solve the problem).

The following implements a thread pool, which executes io_service the run() method [full code] in each worker thread:

classasiothreadpool{ Public: Asiothreadpool (intThreadnum =std::thread::hardware_concurrency ()): Work_ (Newboost::asio::io_service::work (Service_)) {         for(inti =0; i < threadnum; ++i) {threads_.emplace_back ([ This] () {Service_.run ();}); }} asiothreadpool (ConstAsiothreadpool &) =Delete; Asiothreadpool&operator=(ConstAsiothreadpool &) =Delete; Boost::asio::io_service&Getioservice () {returnService_; }    voidStop () {work_.reset ();  for(Auto &T:threads_)                    {T.join (); }            }Private: Boost::asio::io_service service_; Std::unique_ptr<boost::asio::io_service::work>Work_; Std::vector<std::thread>Threads_;};
Lock-Free Sync mode

How to solve the race condition mentioned above? Boost.asio provides io_service::strand : If multiple event handler are distributed through the same Strand object (Dispatch), then these event handler are guaranteed to execute sequentially .
For example, the following example uses strand, so there is no need to use a mutex to ensure that the [full code] is synchronized:

Asiothreadpool Pool (4);//Open 4 ThreadsBoost::asio::steady_timer Timer1{pool.getioservice (), std::chrono::seconds{1}};boost::asio::steady_timer Timer2{pool.getioservice (), std::chrono::seconds{1}};intValue =0; Boost::asio::io_service::strand strand{pool.getioservice ()}; Timer1.async_wait (Strand.wrap ([&value] (ConstBoost::system::error_code &EC) {Std::cout<<"Hello, world!."<< value++ <<Std::endl; }); timer2.async_wait (Strand.wrap ([&value] (ConstBoost::system::error_code &EC) {Std::cout<<"Hello, world!."<< value++ <<Std::endl; }));p ool.stop ();
Multi-threaded Echo Server

The following EchoServer can be used in multi-threading, which is used asio::strand to solve the race problem mentioned earlier [full code]:

classTcpconnection: PublicStd::enable_shared_from_this<tcpconnection> { Public: tcpconnection (Boost::asio::io_service&io_service): socket_ (Io_service), Strand_ (Io_service) {} Tcp::socket&socket () {returnsocket_; }    voidstart () {doread (); }    Private:    voiddoread () {Auto self=Shared_from_this (); Socket_.async_read_some (Boost::asio::buffer (Buffer_, Buffer_.size ()), Strand_.wrap ([ This, Self]                         (Boost::system::error_code EC, std::size_t bytes_transferred) {                             if(!EC)  {Dowrite (bytes_transferred);    }                         })); }    voiddowrite (std::size_t length) {Auto self=Shared_from_this (); Boost::asio::async_write (socket_, Boost::asio::buffer (buffer_, length), Strand_.wrap ([ This, Self] (Boost::system::error_code EC, std::size_t/*bytes_transferred*/)                         {                             if(!EC)  {Doread ();    }                         })); }Private: Tcp::socket socket_;    Boost::asio::io_service::strand Strand_; Std::array<Char,8192>Buffer_;};classechoserver{ Public: Echoserver (Boost::asio::io_service&io_service, unsigned Shortport): Io_service_ (Io_service), Acceptor_ (Io_service, Tcp::endpoint (TCP::V4 (), port)) {do    Accept (); }    voiddoaccept () {Auto Conn= std::make_shared<tcpconnection>(Io_service_); ACCEPTOR_.ASYNC_ACCEPT (Conn-socket (), [ This, Conn]                               (Boost::system::error_code EC) {                                   if(!EC) {conn->start (); }                                    This-doaccept ();    }); }    Private: Boost::asio::io_service&Io_service_; Tcp::acceptor acceptor_;};
Resources
    • The Boost C + + Libraries Chapter 32. Boost.asio
    • A Guide to Getting Started with Boost::asio
    • Strands:use Threads without Explicit Locking
    • Post on ASIO Strand
    • How strands guarantee correct execution of pending events in Boost.asio
    • ASIO C + + library
    • Using Asio with C++11

< turn > Talking about the multithreading model of Boost.asio

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.