• <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.

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

             

            We start by including the necessary header files.

            讓我們從必須包含的頭文件開始。

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

            所有的Asio類只要簡單的包含"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īng)的Boost.Date_Time 頭文件處理時間操作

            
            
            #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的所有程序都至少需要一個提供訪問I/O功能的boost::asio::io_service對象。因此在主函數(shù)中我們做的第一件事就是聲明一個這個類型的對象。

            
            
            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.

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

            
            
            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).

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

              

            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.

             

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

            
            
            t.wait();

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

             最后我們打印出“Hello,world”信息以顯示定時器已經(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.

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

            
            
            #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的異步功能意味著當一個異步操作完成時一個回調(diào)函數(shù)將被調(diào)用。在本程序中我們定義一個名為“print”的函數(shù),在異步等待結(jié)束后這個函數(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.

            接下來,我們調(diào)用boost::asio::deadline_timer::async_wait() 函數(shù)執(zhí)行一個異步等待去取代Timer.1例中的阻塞等待。當調(diào)用這個函數(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對象上調(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()啟動的當前線程所調(diào)用。因此,如果boost::asio::io_service::run() 函數(shù)不執(zhí)行,用于異步等待完成時的回調(diào)函數(shù)(在本例中為print函數(shù))將永遠不會被調(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.

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

             

            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對象將沒有任何事情去做,因此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ù)。

            
            
            #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實現(xiàn)一個重復定時器,你必須在你的回調(diào)函數(shù)中去改變定時器的終止時間,然后開始一個新的異步等待。顯然這意味著回調(diào)函數(shù)必須擁有改變定時器對象的權(quán)限。為此我們?yōu)閜rint函數(shù)增加兩個新參數(shù)。

                一個指向定時器對象的指針

                一個用于當定時器第6次被激活時我們可以中止程序的計數(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.

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

            
            
              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.

            接著,我們推遲定時器的終止時間。通過在原先的終止時間上增加延時,我們可以確保定時器不會在處理回調(diào)函數(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.

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

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

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

            
            
                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.

            為了在定時器第6次被激活時終止程序,我們添加一個新的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.

            在第四步中,當在主函數(shù)中的調(diào)用boost::asio::deadline_timer::async_wait() 函數(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)在聲明一個名為printer的類來取代前個例子程序中的聲明的作為回調(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òu)造函數(shù)使用一個io_service對象的引用來初始化timer_ 成員變量。用來控制關(guān)閉程序的計數(shù)器現(xiàn)在也是類的一個成員變量。

            
            
              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 成員函量都有一個隱式的this指針參數(shù),我們需要把它綁定到函數(shù)上。就像在示例Timer.3中,boost::bind() 使我們的回調(diào)函數(shù)(現(xiàn)在是一個成員函數(shù))轉(zhuǎn)變成一個簽名為void(const boost::system::error_code&)、且可被調(diào)用的函數(shù)對象。

             

            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.

            你可能注意到在這里我們并沒有指定boost::asio::placeholders::error 占位符,這是因為print成員函數(shù)并不接受一個error 對象作為參數(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ù)中我們將打印計數(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.

            這個print成員函數(shù)同示例Timer.3中的print函數(shù)很相似唯一不同的是它現(xiàn)在操作類的數(shù)據(jù)成員而不是作為參數(shù)傳遞來的定時器和計數(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ù)比前面簡單多了。像平常一樣運行io_service對象之前,它現(xiàn)在需要聲明一個局部的printer對象。

            
            
            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 類來創(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.

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

            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開發(fā)應(yīng)用程序最好的方式。下面是Asio在程序中的局限性,尤其是服務(wù)器方面,包括:

              l    

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

              l    

            在大規(guī)模的多處理機系統(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)自己陷入這些局限時,一個可供選擇的方法是創(chuàng)建一個每個線程都調(diào)用boost::asio::io_service::run()線程池。不過,因為這允許并發(fā)操作,當訪問一個共享、非線程安全的資源時我們需要一個同步方式

            
            
            #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.

            讓我們從定義一個名為printer的類開始,這與前一個示例中的類很相似。這個類是上一個例子的擴展,這里我們使用兩個并行的定時器。

            
            
            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.

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

            boost::asio::strand 對象保證:對于通過它來分派執(zhí)行的眾操作中,只有一個操作執(zhí)行完成之后才允許進入下一個操作。這種保證與多少個線程調(diào)用boost::asio::io_service::run()無關(guān)。當然,如果不是通過一個boost::asio::strand對象分派,或者通過其它不同的boost::asio::strand對象分派,這些操作仍舊可能是并發(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.

             當開始同步操作時,每一個回調(diào)句柄都使用boost::asio::strand對象進行“包裝”。boost::asio::strand::wrap() 函數(shù)返回一個新的通過boost::asio::strand對象自動分派的內(nèi)部句柄。通過同一boost::asio::strand對象對句柄進行“包裝”,我們可以保證操作不會并發(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.

            在一個多線程程序中,訪問同一共享資源時,異步操作必須是同步在本例中,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)在被兩個線程調(diào)用:主線程和一個附加線程。這一切依賴于boost::thread對象來完成。

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

            
            
            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 王曉軒 閱讀(7100) 評論(54)  編輯 收藏 引用 所屬分類: C\C++
            一本久道久久综合狠狠爱| 日产精品久久久一区二区| 国产精品亚洲综合专区片高清久久久| 久久精品夜色噜噜亚洲A∨| 模特私拍国产精品久久| 久久九九亚洲精品| 中文字幕精品无码久久久久久3D日动漫| 婷婷综合久久中文字幕蜜桃三电影 | 日韩亚洲欧美久久久www综合网| 国产精品女同一区二区久久| 久久国产色av免费看| 久久久久人妻一区精品| 97精品伊人久久久大香线蕉 | 亚洲精品无码久久千人斩| 99久久久精品| 99久久人妻无码精品系列| 无码人妻久久一区二区三区免费丨| 久久久久国产一级毛片高清版| 久久精品国产男包| 少妇被又大又粗又爽毛片久久黑人| 久久久久中文字幕| 日韩乱码人妻无码中文字幕久久 | 日产久久强奸免费的看| 99久久99久久| 久久国产色AV免费观看| 久久精品国产亚洲av高清漫画 | 久久久久18| 人人狠狠综合久久亚洲婷婷| 精品国产一区二区三区久久久狼| 久久精品国产免费观看| 久久精品国产99国产精品亚洲| 伊人久久大香线蕉AV一区二区| 亚洲精品高清久久| 思思久久99热只有频精品66| 久久综合给合综合久久| 一本色道久久99一综合| 久久青青色综合| 午夜精品久久久久久中宇| 亚洲精品国产字幕久久不卡| 97精品伊人久久久大香线蕉| 亚洲精品蜜桃久久久久久|