• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>
            posts - 6,  comments - 61,  trackbacks - 0

            This tutorial program introduces asio by showing how to perform a blocking wait on a timer.

             這個(gè)示例程序通過(guò)展示在定時(shí)器中執(zhí)行一個(gè)阻塞等待( blocking wait )來(lái)介紹Asio。

             

            We start by including the necessary header files.

            讓我們從必須包含的頭文件開(kāi)始。

            All of the asio classes can be used by simply including the "asio.hpp" header file.

            所有的Asio類只要簡(jiǎn)單的包含"asio.hpp"頭文件便可使用。 

            
            
            #include <iostream>
            #include 
            <boost/asio.hpp>

            Since this example users timers, we need to include the appropriate Boost.Date_Time header file for manipulating times.

            因?yàn)楸境绦蛑惺褂昧硕〞r(shí)器我們需要包含相應(yīng)的Boost.Date_Time 頭文件來(lái)處理時(shí)間操作。

            
            
            #include <boost/date_time/posix_time/posix_time.hpp>

            All programs that use asio need to have at least one boost::asio::io_service object. This class provides access to I/O functionality. We declare an object of this type first thing in the main function.

            使用Asio的所有程序都至少需要一個(gè)提供訪問(wèn)I/O功能的boost::asio::io_service對(duì)象。因此在主函數(shù)中我們做的第一件事就是聲明一個(gè)這個(gè)類型的對(duì)象。

            
            
            int main()
            {
              boost::asio::io_service io;

            Next we declare an object of type boost::asio::deadline_timer. The core asio classes that provide I/O functionality (or as in this case timer functionality) always take a reference to an io_service as their first constructor argument. The second argument to the constructor sets the timer to expire 5 seconds from now.

             接下來(lái)我們聲明一個(gè)boost::asio::deadline_timer類型的對(duì)象。作為Asio的核心類,它提供的I/O功能(在此為定時(shí)器功能)通常用一個(gè)io_service 的引用作為其構(gòu)造函數(shù)的第一個(gè)參數(shù)。第二個(gè)參數(shù)設(shè)置一個(gè)從現(xiàn)在開(kāi)始5秒后終止的定時(shí)器。

            
            
            boost::asio::deadline_timer t(io, boost::posix_time::seconds(5));

            In this simple example we perform a blocking wait on the timer. That is, the call to boost::asio::deadline_timer::wait() will not return until the timer has expired, 5 seconds after it was created (i.e. not from when the wait starts).

            在這個(gè)簡(jiǎn)單的程序中,我們用定時(shí)器演示一個(gè)阻塞等待。boost::asio::deadline_timer::wait()函數(shù)調(diào)用直到定時(shí)器終止(從定時(shí)器被創(chuàng)建算起,五秒后終止)才會(huì)返回

              

            A deadline timer is always in one of two states: "expired" or "not expired". If the boost::asio::deadline_timer::wait() function is called on an expired timer, it will return immediately.

             

            一個(gè)deadline timer 通常是下面兩種狀態(tài)中的一種:"expired(終止)" 或"not expired(不終止)"。如果boost::asio::deadline_timer::wait()函數(shù)被一個(gè)已經(jīng)終止的定時(shí)器調(diào)用, 它將立即返回。

            
            
            t.wait();

            Finally we print the obligatory "Hello, world!" message to show when the timer has expired.

             最后我們打印出“Hello,world”信息以顯示定時(shí)器已經(jīng)終止。

            
            
             std::cout << "Hello, world! ";

              
            return 0;
            }

            See the full source listing

            查看本例的全部源碼:

             

             //
            // timer.cpp
            // ~~~~~~~~~
            //
            // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
            //
            // Distributed under the Boost Software License, Version 1.0. (See accompanying
            // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
            //

            #include 
            <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            int main()
            {
              boost::asio::io_service io;

              boost::asio::deadline_timer t(io, boost::posix_time::seconds(
            5));
              t.wait();

              std::cout 
            << "Hello, world! ";

              
            return 0;
            }

            This tutorial program demonstrates how to use asio's asynchronous callback functionality by modifying the program from tutorial Timer.1 to perform an asynchronous wait on the timer.

             這個(gè)示例程序示范了如何通過(guò)修改Timer.1 中的程序,使用Asio的異步回調(diào)功能在定時(shí)器中演示一個(gè)異步等待。

            
            
            #include <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            Using asio's asynchronous functionality means having a callback function that will be called when an asynchronous operation completes. In this program we define a function called print to be called when the asynchronous wait finishes.

            使用Asio的異步功能意味著當(dāng)一個(gè)異步操作完成時(shí)一個(gè)回調(diào)函數(shù)將被調(diào)用。在本程序中我們定義一個(gè)名為“print”的函數(shù),在異步等待結(jié)束后這個(gè)函數(shù)將被調(diào)用。

            
            
            void print(const boost::system::error_code& /*e*/)
            {
              std::cout 
            << "Hello, world! ";
            }

            int main()
            {
              boost::asio::io_service io;

              boost::asio::deadline_timer t(io, boost::posix_time::seconds(
            5));

            Next, instead of doing a blocking wait as in tutorial Timer.1, we call the boost::asio::deadline_timer::async_wait() function to perform an asynchronous wait. When calling this function we pass the print callback handler that was defined above.

            接下來(lái),我們調(diào)用boost::asio::deadline_timer::async_wait() 函數(shù)執(zhí)行一個(gè)異步等待去取代Timer.1例中的阻塞等待。當(dāng)調(diào)用這個(gè)函數(shù)時(shí)我們傳入上面定義的print回調(diào)句柄。

            
            
              t.async_wait(print);

            Finally, we must call the boost::asio::io_service::run() member function on the io_service object.

            最后,我們必須在io_service對(duì)象上調(diào)用boost::asio::io_service::run() 成員函數(shù)。

             

            The asio library provides a guarantee that callback handlers will only be called from threads that are currently calling boost::asio::io_service::run(). Therefore unless the boost::asio::io_service::run() function is called the callback for the asynchronous wait completion will never be invoked.

            Asio保證回調(diào)句柄僅僅能被boost::asio::io_service::run()啟動(dòng)的當(dāng)前線程所調(diào)用。因此,如果boost::asio::io_service::run() 函數(shù)不執(zhí)行,用于異步等待完成時(shí)的回調(diào)函數(shù)(在本例中為print函數(shù))將永遠(yuǎn)不會(huì)被調(diào)用。

             

            The boost::asio::io_service::run() function will also continue to run while there is still "work" to do. In this example, the work is the asynchronous wait on the timer, so the call will not return until the timer has expired and the callback has completed.

             當(dāng)仍舊有“工作”可做時(shí),boost::asio::io_service::run() 函數(shù)會(huì)繼續(xù)運(yùn)行。在本例中,“工作”是定時(shí)器的異步等待,因此,直到定時(shí)器終止和回調(diào)函數(shù)執(zhí)行完成,程序才會(huì)返回。

             

            It is important to remember to give the io_service some work to do before calling boost::asio::io_service::run(). For example, if we had omitted the above call to boost::asio::deadline_timer::async_wait(), the io_service would not have had any work to do, and consequently boost::asio::io_service::run() would have returned immediately.

             

            在調(diào)用boost::asio::io_service::run()之前確保給io_service 一些工作去做,這非常重要。例如,如果我們省略了上面調(diào)用的boost::asio::deadline_timer::async_wait()函數(shù),io_service對(duì)象將沒(méi)有任何事情去做,因此boost::asio::io_service::run() 將立即返回。

             

            
            
              io.run();

              
            return 0;
            }

            See the full source listing

             查看本例的全部源碼:

             

            //
            // timer.cpp
            // ~~~~~~~~~
            //
            // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
            //
            // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
            //

            #include 
            <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            void print(const boost::system::error_code& /*e*/)
            {
              std::cout 
            << "Hello, world! ";
            }

            int main()
            {
              boost::asio::io_service io;

              boost::asio::deadline_timer t(io, boost::posix_time::seconds(
            5));
              t.async_wait(print);

              io.run();

              
            return 0;
            }

            In this tutorial we will modify the program from tutorial Timer.2 so that the timer fires once a second. This will show how to pass additional parameters to your handler function.

             在本示例程序中我們將修改Timer.2中的例子,使定時(shí)器每秒被激活一次。例子將示范如何給你的函數(shù)指針傳遞附加參數(shù)。

            
            
            #include <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/bind.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            To implement a repeating timer using asio you need to change the timer's expiry time in your callback function, and to then start a new asynchronous wait. Obviously this means that the callback function will need to be able to access the timer object. To this end we add two new parameters to the print function:

            • A pointer to a timer object.
            • A counter so that we can stop the program when the timer fires for the sixth time.

            使用Asio實(shí)現(xiàn)一個(gè)重復(fù)定時(shí)器,你必須在你的回調(diào)函數(shù)中去改變定時(shí)器的終止時(shí)間,然后開(kāi)始一個(gè)新的異步等待。顯然這意味著回調(diào)函數(shù)必須擁有改變定時(shí)器對(duì)象的權(quán)限。為此我們?yōu)閜rint函數(shù)增加兩個(gè)新參數(shù)。

                一個(gè)指向定時(shí)器對(duì)象的指針

                一個(gè)用于當(dāng)定時(shí)器第6次被激活時(shí)我們可以中止程序的計(jì)數(shù)器

            
            
            void print(const boost::system::error_code& /*e*/,
                boost::asio::deadline_timer
            * t, int* count)
            {

            As mentioned above, this tutorial program uses a counter to stop running when the timer fires for the sixth time. However you will observe that there is no explicit call to ask the io_service to stop. Recall that in tutorial Timer.2 we learnt that the boost::asio::io_service::run() function completes when there is no more "work" to do. By not starting a new asynchronous wait on the timer when count reaches 5, the io_service will run out of work and stop running.

            如上所示示例程序使用了一個(gè)計(jì)數(shù)器,當(dāng)定時(shí)器被第6次激活時(shí),用來(lái)中止程序。然而,你將看到這里并沒(méi)有顯式地要求io_service對(duì)象中止。回憶示例2中,當(dāng)沒(méi)有更多“工作”去做時(shí),boost::asio::io_service::run() 函數(shù)完成。在計(jì)數(shù)器達(dá)到5時(shí),定時(shí)器并沒(méi)有啟動(dòng)一個(gè)新的異步等待。該io_service執(zhí)行完工作后停止運(yùn)行。

            
            
              if (*count < 5)
              {
                std::cout 
            << *count << " ";
                
            ++(*count);

            Next we move the expiry time for the timer along by one second from the previous expiry time. By calculating the new expiry time relative to the old, we can ensure that the timer does not drift away from the whole-second mark due to any delays in processing the handler.

            接著,我們推遲定時(shí)器的終止時(shí)間。通過(guò)在原先的終止時(shí)間上增加延時(shí),我們可以確保定時(shí)器不會(huì)在處理回調(diào)函數(shù)所需時(shí)間內(nèi)到期。

            
            
                t->expires_at(t->expires_at() + boost::posix_time::seconds(1));

            Then we start a new asynchronous wait on the timer. As you can see, the boost::bind() function is used to associate the extra parameters with your callback handler. The boost::asio::deadline_timer::async_wait() function expects a handler function (or function object) with the signature void(const boost::system::error_code&). Binding the additional parameters converts your print function into a function object that matches the signature correctly.

            See the Boost.Bind documentation for more information on how to use boost::bind().

            In this example, the boost::asio::placeholders::error argument to boost::bind() is a named placeholder for the error object passed to the handler. When initiating the asynchronous operation, and if using boost::bind(), you must specify only the arguments that match the handler's parameter list. In tutorial Timer.4 you will see that this placeholder may be elided if the parameter is not needed by the callback handler.

            接著我們?cè)诙〞r(shí)器中啟動(dòng)一個(gè)新的異步等待。我們必須使用boost::bind() 函數(shù)給你的回調(diào)函數(shù)綁定額外的參數(shù),因?yàn)閎oost::asio::deadline_timer::async_wait() 函數(shù)只期望得到一個(gè)擁用void(const boost::system::error_code&)簽名的函數(shù)指針(或函數(shù)對(duì)象)。為你的print函數(shù)綁定附加的參數(shù)后,就成簽名精確匹配的函數(shù)對(duì)象。

            查看Boost.Bind文檔以獲得更多如何使用boost::bind()的信息。

            在本例中,boost::bind()的boost::asio::placeholders::error參數(shù)是為了給回調(diào)函數(shù)傳入一個(gè)error對(duì)象。當(dāng)開(kāi)始異步操作時(shí),如果使用boost::bind(),你必須指定和回調(diào)函數(shù)的參數(shù)列表相匹配的一個(gè)參數(shù)。在示例4中,如果在回調(diào)函數(shù)中,這個(gè)參數(shù)不是必需的,這個(gè)占位符會(huì)被省略。

            
            
                t->async_wait(boost::bind(print,
                      boost::asio::placeholders::error, t, count));
              }
            }

            int main()
            {
              boost::asio::io_service io;

            A new count variable is added so that we can stop the program when the timer fires for the sixth time.

            為了在定時(shí)器第6次被激活時(shí)終止程序,我們添加一個(gè)新的count變量。

            
            
              int count = 0;
              boost::asio::deadline_timer t(io, boost::posix_time::seconds(
            1));

            As in Step 4, when making the call to boost::asio::deadline_timer::async_wait() from main we bind the additional parameters needed for the print function.

            在第四步中,當(dāng)在主函數(shù)中的調(diào)用boost::asio::deadline_timer::async_wait() 函數(shù)時(shí),我們綁定print函數(shù)所需要的附加參數(shù)。

            
            
              t.async_wait(boost::bind(print,
                    boost::asio::placeholders::error, 
            &t, &count));

              io.run();

            Finally, just to prove that the count variable was being used in the print handler function, we will print out its new value.

            最后,為了證明count變量在print函數(shù)句柄中被使用,我們打印出它的值。

            
            
              std::cout << "Final count is " << count << " ";

              
            return 0;
            }

            See the full source listing

            查看本例的全部源碼:

             

            //
            // timer.cpp
            // ~~~~~~~~~
            //
            // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
            //
            // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
            //

            #include 
            <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/bind.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            void print(const boost::system::error_code& /*e*/,
                boost::asio::deadline_timer
            * t, int* count)
            {
              
            if (*count < 5)
              {
                std::cout 
            << *count << " ";
                
            ++(*count);

                t
            ->expires_at(t->expires_at() + boost::posix_time::seconds(1));
                t
            ->async_wait(boost::bind(print,
                      boost::asio::placeholders::error, t, count));
              }
            }

            int main()
            {
              boost::asio::io_service io;

              
            int count = 0;
              boost::asio::deadline_timer t(io, boost::posix_time::seconds(
            1));
              t.async_wait(boost::bind(print,
                    boost::asio::placeholders::error, 
            &t, &count));

              io.run();

              std::cout 
            << "Final count is " << count << " ";

              
            return 0;
            }

            In this tutorial we will see how to use a class member function as a callback handler. The program should execute identically to the tutorial program from tutorial Timer.3.

             在本例中我們將看到怎樣使用類成員函數(shù)作為回調(diào)句柄。程序完成和Timer.3完全同樣的功能。

            
            
            #include <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/bind.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            Instead of defining a free function print as the callback handler, as we did in the earlier tutorial programs, we now define a class called printer.

             我們現(xiàn)在聲明一個(gè)名為printer的類來(lái)取代前個(gè)例子程序中的聲明的作為回調(diào)句柄的自由函數(shù)print。

            
            
            class printer
            {
            public:

            The constructor of this class will take a reference to the io_service object and use it when initialising the timer_ member. The counter used to shut down the program is now also a member of the class.

            這個(gè)類的構(gòu)造函數(shù)使用一個(gè)io_service對(duì)象的引用來(lái)初始化timer_ 成員變量。用來(lái)控制關(guān)閉程序的計(jì)數(shù)器現(xiàn)在也是類的一個(gè)成員變量。

            
            
              printer(boost::asio::io_service& io)
                : timer_(io, boost::posix_time::seconds(
            1)),
                  count_(
            0)
              {

            The boost::bind() function works just as well with class member functions as with free functions. Since all non-static class member functions have an implicit this parameter, we need to bind this to the function. As in tutorial Timer.3, boost::bind() converts our callback handler (now a member function) into a function object that can be invoked as though it has the signature void(const boost::system::error_code&).

             正如自由函數(shù)一樣,boost::bind() 也可以很好地用在類成員函數(shù)上。所有的non-static 成員函量都有一個(gè)隱式的this指針參數(shù),我們需要把它綁定到函數(shù)上。就像在示例Timer.3中,boost::bind() 使我們的回調(diào)函數(shù)(現(xiàn)在是一個(gè)成員函數(shù))轉(zhuǎn)變成一個(gè)簽名為void(const boost::system::error_code&)、且可被調(diào)用的函數(shù)對(duì)象。

             

            You will note that the boost::asio::placeholders::error placeholder is not specified here, as the print member function does not accept an error object as a parameter.

            你可能注意到在這里我們并沒(méi)有指定boost::asio::placeholders::error 占位符,這是因?yàn)閜rint成員函數(shù)并不接受一個(gè)error 對(duì)象作為參數(shù)。

            
            
                timer_.async_wait(boost::bind(&printer::print, this));
              }

            In the class destructor we will print out the final value of the counter.

             在類的析構(gòu)函數(shù)中我們將打印計(jì)數(shù)器變量的最終值。

            
            
              ~printer()
              {
                std::cout 
            << "Final count is " << count_ << " ";
              }

            The print member function is very similar to the print function from tutorial Timer.3, except that it now operates on the class data members instead of having the timer and counter passed in as parameters.

            這個(gè)print成員函數(shù)同示例Timer.3中的print函數(shù)很相似唯一不同的是它現(xiàn)在操作類的數(shù)據(jù)成員而不是作為參數(shù)傳遞來(lái)的定時(shí)器和計(jì)數(shù)器

            
            
              void print()
              {
                
            if (count_ < 5)
                {
                  std::cout 
            << count_ << " ";
                  
            ++count_;

                  timer_.expires_at(timer_.expires_at() 
            + boost::posix_time::seconds(1));
                  timer_.async_wait(boost::bind(
            &printer::print, this));
                }
              }

            private:
              boost::asio::deadline_timer timer_;
              
            int count_;
            };

            The main function is much simpler than before, as it now declares a local printer object before running the io_service as normal.

            主函數(shù)比前面簡(jiǎn)單多了。像平常一樣運(yùn)行io_service對(duì)象之前,它現(xiàn)在需要聲明一個(gè)局部的printer對(duì)象。

            
            
            int main()
            {
              boost::asio::io_service io;
              printer p(io);
              io.run();

              
            return 0;
            }

            See the full source listing

             查看本例的全部源碼:

             

            //
            // timer.cpp
            // ~~~~~~~~~
            //
            // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
            //
            // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
            //

            #include 
            <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/bind.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            class printer
            {
            public:
              printer(boost::asio::io_service
            & io)
                : timer_(io, boost::posix_time::seconds(
            1)),
                  count_(
            0)
              {
                timer_.async_wait(boost::bind(
            &printer::print, this));
              }

              
            ~printer()
              {
                std::cout 
            << "Final count is " << count_ << " ";
              }

              
            void print()
              {
                
            if (count_ < 5)
                {
                  std::cout 
            << count_ << " ";
                  
            ++count_;

                  timer_.expires_at(timer_.expires_at() 
            + boost::posix_time::seconds(1));
                  timer_.async_wait(boost::bind(
            &printer::print, this));
                }
              }

            private:
              boost::asio::deadline_timer timer_;
              
            int count_;
            };

            int main()
            {
              boost::asio::io_service io;
              printer p(io);
              io.run();

              
            return 0;
            }

            This tutorial demonstrates the use of the boost::asio::strand class to synchronise callback handlers in a multithreaded program.

             本示例程序示范了使用boost::asio::strand 類來(lái)創(chuàng)建多線程程序中的同步回調(diào)句柄。

            The previous four tutorials avoided the issue of handler synchronisation by calling the boost::asio::io_service::run() function from one thread only. As you already know, the asio library provides a guarantee that callback handlers will only be called from threads that are currently calling boost::asio::io_service::run(). Consequently, calling boost::asio::io_service::run() from only one thread ensures that callback handlers cannot run concurrently.

             前四個(gè)例程只是在線程下使用 boost::asio::io_service::run() 函數(shù)來(lái)避免處理函同步。如你所見(jiàn),Asio庫(kù)保證回調(diào)句柄僅能被當(dāng)前正在調(diào)用boost::asio::io_service::run()函數(shù)的線程調(diào)用。因此,在線程中調(diào)用boost::asio::io_service::run()能確?;卣{(diào)句柄不被并發(fā)運(yùn)行。

            The single threaded approach is usually the best place to start when developing applications using asio. The downside is the limitations it places on programs, particularly servers, including:

            • Poor responsiveness when handlers can take a long time to complete.
            • An inability to scale on multiprocessor systems.

             單線程通常是使用Asio開(kāi)發(fā)應(yīng)用程序最好的方式。下面是Asio在程序中的局限性,尤其是服務(wù)器方面,包括:

              l    

            操作需要較長(zhǎng)時(shí)間處理才能完成時(shí)弱響應(yīng)  

              l    

            在大規(guī)模的多處理機(jī)系統(tǒng)中表現(xiàn)不佳 

             

             

            If you find yourself running into these limitations, an alternative approach is to have a pool of threads calling boost::asio::io_service::run(). However, as this allows handlers to execute concurrently, we need a method of synchronisation when handlers might be accessing a shared, thread-unsafe resource.

            如果你發(fā)現(xiàn)自己陷入這些局限時(shí),一個(gè)可供選擇的方法是創(chuàng)建一個(gè)每個(gè)線程都調(diào)用boost::asio::io_service::run()線程池。不過(guò),因?yàn)檫@允許并發(fā)操作,當(dāng)訪問(wèn)一個(gè)共享、非線程安全的資源時(shí)我們需要一個(gè)同步方式

            
            
            #include <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/thread.hpp>
            #include 
            <boost/bind.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            We start by defining a class called printer, similar to the class in the previous tutorial. This class will extend the previous tutorial by running two timers in parallel.

            讓我們從定義一個(gè)名為printer的類開(kāi)始,這與前一個(gè)示例中的類很相似。這個(gè)類是上一個(gè)例子的擴(kuò)展,這里我們使用兩個(gè)并行的定時(shí)器。

            
            
            class printer
            {
            public:

            In addition to initialising a pair of boost::asio::deadline_timer members, the constructor initialises the strand_ member, an object of type boost::asio::strand.

            An boost::asio::strand guarantees that, for those handlers that are dispatched through it, an executing handler will be allowed to complete before the next one is started. This is guaranteed irrespective of the number of threads that are calling boost::asio::io_service::run(). Of course, the handlers may still execute concurrently with other handlers that were not dispatched through an boost::asio::strand, or were dispatched through a different boost::asio::strand object.

             除了初始化一對(duì)boost::asio::deadline_timer 成員變量外,構(gòu)造函數(shù)還初始化一個(gè)boost::asio::strand類型strand_成員變量

            boost::asio::strand 對(duì)象保證:對(duì)于通過(guò)它來(lái)分派執(zhí)行的眾操作中,只有一個(gè)操作執(zhí)行完成之后才允許進(jìn)入下一個(gè)操作。這種保證與多少個(gè)線程調(diào)用boost::asio::io_service::run()無(wú)關(guān)。當(dāng)然,如果不是通過(guò)一個(gè)boost::asio::strand對(duì)象分派,或者通過(guò)其它不同的boost::asio::strand對(duì)象分派,這些操作仍舊可能是并發(fā)的。

            
            
              printer(boost::asio::io_service& io)
                : strand_(io),
                  timer1_(io, boost::posix_time::seconds(
            1)),
                  timer2_(io, boost::posix_time::seconds(
            1)),
                  count_(
            0)
              {

            When initiating the asynchronous operations, each callback handler is "wrapped" using the boost::asio::strand object. The boost::asio::strand::wrap() function returns a new handler that automatically dispatches its contained handler through the boost::asio::strand object. By wrapping the handlers using the same boost::asio::strand, we are ensuring that they cannot execute concurrently.

             當(dāng)開(kāi)始同步操作時(shí),每一個(gè)回調(diào)句柄都使用boost::asio::strand對(duì)象進(jìn)行“包裝”。boost::asio::strand::wrap() 函數(shù)返回一個(gè)新的通過(guò)boost::asio::strand對(duì)象自動(dòng)分派的內(nèi)部句柄。通過(guò)同一boost::asio::strand對(duì)象對(duì)句柄進(jìn)行“包裝”,我們可以保證操作不會(huì)并發(fā)執(zhí)行。

            
            
                timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
                timer2_.async_wait(strand_.wrap(boost::bind(
            &printer::print2, this)));
              }

              
            ~printer()
              {
                std::cout 
            << "Final count is " << count_ << " ";
              }

            In a multithreaded program, the handlers for asynchronous operations should be synchronised if they access shared resources. In this tutorial, the shared resources used by the handlers (print1 and print2) are std::cout and the count_ data member.

            在一個(gè)多線程程序中,當(dāng)訪問(wèn)同一共享資源時(shí),異步操作必須是同步在本例中,print1print2函數(shù)使用的共享資源std::coutcount_數(shù)據(jù)成員。

            
            
              void print1()
              {
                
            if (count_ < 10)
                {
                  std::cout 
            << "Timer 1: " << count_ << " ";
                  
            ++count_;

                  timer1_.expires_at(timer1_.expires_at() 
            + boost::posix_time::seconds(1));
                  timer1_.async_wait(strand_.wrap(boost::bind(
            &printer::print1, this)));
                }
              }

              
            void print2()
              {
                
            if (count_ < 10)
                {
                  std::cout 
            << "Timer 2: " << count_ << " ";
                  
            ++count_;

                  timer2_.expires_at(timer2_.expires_at() 
            + boost::posix_time::seconds(1));
                  timer2_.async_wait(strand_.wrap(boost::bind(
            &printer::print2, this)));
                }
              }

            private:
              boost::asio::strand strand_;
              boost::asio::deadline_timer timer1_;
              boost::asio::deadline_timer timer2_;
              
            int count_;
            };

            The main function now causes boost::asio::io_service::run() to be called from two threads: the main thread and one additional thread. This is accomplished using an boost::thread object.

            Just as it would with a call from a single thread, concurrent calls to boost::asio::io_service::run() will continue to execute while there is "work" left to do. The background thread will not exit until all asynchronous operations have completed.

             在主函數(shù)中,boost::asio::io_service::run() 現(xiàn)在被兩個(gè)線程調(diào)用:主線程和一個(gè)附加線程。這一切依賴于boost::thread對(duì)象來(lái)完成。

            正如它被一個(gè)單線程調(diào)用一樣,boost::asio::io_service::run() 的并發(fā)調(diào)用會(huì)一直持續(xù)到無(wú)任何“工作”可做。后臺(tái)線程直到所有異步操作完成會(huì)退出。

            
            
            int main()
            {
              boost::asio::io_service io;
              printer p(io);
              boost::thread t(boost::bind(
            &boost::asio::io_service::run, &io));
              io.run();
              t.join();

              
            return 0;
            }

            See the full source listing

             查看本例的全部源碼:

             

            
            
            //
            // timer.cpp
            // ~~~~~~~~~
            //
            // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
            //
            // Distributed under the Boost Software License, Version 1.0. (See accompanying
            // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
            //

            #include 
            <iostream>
            #include 
            <boost/asio.hpp>
            #include 
            <boost/thread.hpp>
            #include 
            <boost/bind.hpp>
            #include 
            <boost/date_time/posix_time/posix_time.hpp>

            class printer
            {
            public:
              printer(boost::asio::io_service
            & io)
                : strand_(io),
                  timer1_(io, boost::posix_time::seconds(
            1)),
                  timer2_(io, boost::posix_time::seconds(
            1)),
                  count_(
            0)
              {
                timer1_.async_wait(strand_.wrap(boost::bind(
            &printer::print1, this)));
                timer2_.async_wait(strand_.wrap(boost::bind(
            &printer::print2, this)));
              }

              
            ~printer()
              {
                std::cout 
            << "Final count is " << count_ << " ";
              }

              
            void print1()
              {
                
            if (count_ < 10)
                {
                  std::cout 
            << "Timer 1: " << count_ << " ";
                  
            ++count_;

                  timer1_.expires_at(timer1_.expires_at() 
            + boost::posix_time::seconds(1));
                  timer1_.async_wait(strand_.wrap(boost::bind(
            &printer::print1, this)));
                }
              }

              
            void print2()
              {
                
            if (count_ < 10)
                {
                  std::cout 
            << "Timer 2: " << count_ << " ";
                  
            ++count_;

                  timer2_.expires_at(timer2_.expires_at() 
            + boost::posix_time::seconds(1));
                  timer2_.async_wait(strand_.wrap(boost::bind(
            &printer::print2, this)));
                }
              }

            private:
              boost::asio::strand strand_;
              boost::asio::deadline_timer timer1_;
              boost::asio::deadline_timer timer2_;
              
            int count_;
            };

            int main()
            {
              boost::asio::io_service io;
              printer p(io);
              boost::thread t(boost::bind(
            &boost::asio::io_service::run, &io));
              io.run();
              t.join();

              
            return 0;
            }
            posted on 2008-04-20 01:17 王曉軒 閱讀(7075) 評(píng)論(54)  編輯 收藏 引用 所屬分類: C\C++
            久久99精品久久久久久| 久久综合视频网站| 久久噜噜久久久精品66| 伊人久久五月天| 国产高潮国产高潮久久久| 99精品伊人久久久大香线蕉| 亚洲国产成人久久一区久久| 久久久久99精品成人片欧美 | www.久久精品| 久久精品成人| 久久青青草原精品国产| 久久精品国产一区二区三区| 亚洲乱码中文字幕久久孕妇黑人| 国产午夜精品理论片久久影视| 四虎影视久久久免费| 99久久99久久精品免费看蜜桃 | 久久人人爽人人爽人人AV东京热| 91久久福利国产成人精品| 久久久久久精品成人免费图片| 久久综合中文字幕| 狠狠色婷婷久久综合频道日韩| 国产精品免费看久久久香蕉| 亚洲国产欧美国产综合久久| 精品国产综合区久久久久久 | 一本大道久久香蕉成人网| 国产综合久久久久| 色妞色综合久久夜夜| 99久久久久| 无码国内精品久久人妻蜜桃| 热RE99久久精品国产66热| 嫩草影院久久国产精品| 久久综合噜噜激激的五月天| 亚洲人AV永久一区二区三区久久| 久久天堂电影网| 97久久久久人妻精品专区| 99精品国产99久久久久久97| 性高湖久久久久久久久AAAAA| 伊人热人久久中文字幕| 国内精品伊人久久久久| 色婷婷综合久久久久中文| 狠狠色丁香久久婷婷综合图片|