boost::asio::io_service(之一)

boost::asio::io_service

/// Provides core I/O functionality.
/**
 * The io_service class provides the core I/O functionality for users of the
 * asynchronous I/O objects, including:
 * io_service類爲下面的異步對象提供了核心的I/O操作函數
 *
 * @li boost::asio::ip::tcp::socket
 * @li boost::asio::ip::tcp::acceptor
 * @li boost::asio::ip::udp::socket
 * @li boost::asio::deadline_timer.
 *
 * The io_service class also includes facilities intended for developers of
 * custom asynchronous services.
 *
 * @par Thread Safety
 * @e Distinct @e objects: Safe.@n
 * @e Shared @e objects: Safe, with the specific exceptions of the reset() and
 * notify_fork() functions. Calling reset() while there are unfinished run(),
 * run_one(), poll() or poll_one() calls results in undefined behaviour. The
 * notify_fork() function should not be called while any io_service function,
 * or any function on an I/O object that is associated with the io_service, is
 * being called in another thread.
 * 當run、run_one、poll、poll_one這些函數沒有完成時,調用reset會引起未定義的行爲。
 * 如果有其它進程正在調用io_service的任何函數或者任何I/O對象的函數(這些I/O對象與
 * io_service有關),則一定不要調用notify_fork()函數。
 *
 * @par Concepts:
 * Dispatcher.
 *
 * @par Synchronous and asynchronous operations
 *
 * Synchronous operations on I/O objects implicitly run the io_service object
 * for an individual operation. The io_service functions run(), run_one(),
 * poll() or poll_one() must be called for the io_service to perform
 * asynchronous operations on behalf of a C++ program. Notification that an
 * asynchronous operation has completed is delivered by invocation of the
 * associated handler. Handlers are invoked only by a thread that is currently
 * calling any overload of run(), run_one(), poll() or poll_one() for the
 * io_service.
 * 在I/O對象上的同步操作會隱式的調用io_service對象。在c++程序中,io_service如果要完成異步操作,必須
 * 調用run、run_one、poll、poll_one。 異步操作完成是指分發調用相關的處理句柄。 
 *
 * @par Effect of exceptions thrown from handlers
 *
 * If an exception is thrown from a handler, the exception is allowed to
 * propagate through the throwing thread's invocation of run(), run_one(),
 * poll() or poll_one(). No other threads that are calling any of these
 * functions are affected. It is then the responsibility of the application to
 * catch the exception.
 * 假如一個回調句柄拋出異常,這個異常可以傳播給那些調用run、run_one、poll、pool_one
 * 的進程,其它沒有調用這些函數的進程不受影響。然後應用程序有責任捕捉這個異常。
 *
 * After the exception has been caught, the run(), run_one(), poll() or
 * poll_one() call may be restarted @em without the need for an intervening
 * call to reset(). This allows the thread to rejoin the io_service object's
 * thread pool without impacting any other threads in the pool.
 * 捕捉異常後,run、run_one、poll、poll_one可以被重新調用,不需要再調用reset。
 * 這允許進程重新加入io_service對象的進程池,從而不影響其他已經在進程池中的進程。
 * For example:
 *
 * @code
 * boost::asio::io_service io_service;
 * ...
 * for (;;)
 * {
 *   try
 *   {
 *     io_service.run();
 *     break; // run() exited normally
 *   }
 *   catch (my_exception& e)
 *   {
 *     // Deal with exception as appropriate.
 *   }
 * }
 * @endcode
 *
 * @par Stopping the io_service from running out of work
 *
 * Some applications may need to prevent an io_service object's run() call from
 * returning when there is no more work to do. For example, the io_service may
 * be being run in a background thread that is launched prior to the
 * application's asynchronous operations. The run() call may be kept running by
 * creating an object of type boost::asio::io_service::work:
 * //add by wyp// work類可以阻止io_service的run函數在無任何任務時返回。這在後臺服務的進程
 * 中經常用到。
 *
 * @code boost::asio::io_service io_service;
 * boost::asio::io_service::work work(io_service);
 * ... @endcode
 *
 * To effect a shutdown, the application will then need to call the io_service
 * object's stop() member function. This will cause the io_service run() call
 * to return as soon as possible, abandoning unfinished operations and without
 * permitting ready handlers to be dispatched.
 * //stop()函數可以停止io_service,這將導致run()函數立即返回,那些未完成的操作被終止,
 * 那些滿足條件的句柄不能被分發。
 *
 * Alternatively, if the application requires that all operations and handlers
 * be allowed to finish normally, the work object may be explicitly destroyed.
 *
 * @code boost::asio::io_service io_service;
 * auto_ptr<boost::asio::io_service::work> work(
 *     new boost::asio::io_service::work(io_service));
 * ...
 * work.reset(); // Allow run() to exit. @endcode
 *
 * @par The io_service class and I/O services
 *
 * Class io_service implements an extensible, type-safe, polymorphic set of I/O
 * services, indexed by service type. An object of class io_service must be
 * initialised before I/O objects such as sockets, resolvers and timers can be
 * used. These I/O objects are distinguished by having constructors that accept
 * an @c io_service& parameter.
 * io_service實現了可擴張的、類型安全的、多態的I/O服務集,按服務類型索引。在使用I/O對象
 * 之前,必須初始化一個io_service對象。I/O對象通過接受一個io_service對象的引用區分。
 *
 * I/O services exist to manage the logical interface to the operating system on
 * behalf of the I/O objects. In particular, there are resources that are shared
 * across a class of I/O objects. For example, timers may be implemented in
 * terms of a single timer queue. The I/O services manage these shared
 * resources.
 * 
 * Access to the services of an io_service is via three function templates,
 * use_service(), add_service() and has_service().
 *
 * In a call to @c use_service<Service>(), the type argument chooses a service,
 * making available all members of the named type. If @c Service is not present
 * in an io_service, an object of type @c Service is created and added to the
 * io_service. A C++ program can check if an io_service implements a
 * particular service with the function template @c has_service<Service>().
 * 通過調用use_service,類型參數選擇一個Service,這種類型的所有成員就可以使用了。
 * 如果Service不在一個io_service,就會創建一個type的Service,並把這個Service加入到io_service。
 * 在c++程序中,我們可以用has_service來檢查一個io_service對象是否存在一個特殊的service。
 *
 * Service objects may be explicitly added to an io_service using the function
 * template @c add_service<Service>(). If the @c Service is already present, the
 * service_already_exists exception is thrown. If the owner of the service is
 * not the same object as the io_service parameter, the invalid_service_owner
 * exception is thrown.
 * Service 對象可以通過add_service加入io_service對象中,加入這個Service對象已經存在,
 * 會拋出一個service已經存在的異常。 如果service的擁有者不和參數io_service是同一個對象,
 * 會拋出無效的service擁有者的異常。
 *
 * Once a service reference is obtained from an io_service object by calling
 * use_service(), that reference remains usable as long as the owning io_service
 * object exists.
 * 一旦通過調用use_service獲得一個service的引用,那麼這個引用一直有效,只要這個service的
 * 擁有者存在。
 *
 * All I/O service implementations have io_service::service as a public base
 * class. Custom I/O services may be implemented by deriving from this class and
 * then added to an io_service using the facilities described above.
 */
class io_service
  : private noncopyable
{
private:
  typedef detail::io_service_impl impl_type;
#if defined(BOOST_ASIO_HAS_IOCP)
  friend class detail::win_iocp_overlapped_ptr;
#endif

public:
  class work;
  friend class work;

  class id;

  class service;

  class strand;

  /// Constructor.
  BOOST_ASIO_DECL io_service();

  /// Constructor.
  /**
   * Construct with a hint about the required level of concurrency(併發性).
   *
   * @param concurrency_hint A suggestion to the implementation on how many
   * threads it should allow to run simultaneously.//同時運行多少個進程
   */
  BOOST_ASIO_DECL explicit io_service(std::size_t concurrency_hint);

  /// Destructor.
  /**
   * On destruction, the io_service performs the following sequence of
   * operations:
   *
   * @li For each service object @c svc in the io_service set, in reverse order
   * of the beginning of service object lifetime, performs
   * @c svc->shutdown_service().
   * 按進入隊列的順序,反序的調用service的shutdown_service
   *
   * @li Uninvoked handler objects that were scheduled for deferred invocation
   * on the io_service, or any associated strand, are destroyed.
   * 銷燬延遲調用的句柄對象和相關的strand
   *
   * @li For each service object @c svc in the io_service set, in reverse order
   * of the beginning of service object lifetime, performs
   * <tt>delete static_cast<io_service::service*>(svc)</tt>.
   * 按進入隊列的順序,反序的銷燬service對象
   *
   * @note The destruction sequence described above permits programs to      
   * simplify their resource management by using @c shared_ptr<>. Where an   
   * object's lifetime is tied to the lifetime of a connection (or some other
   * sequence of asynchronous operations), a @c shared_ptr to the object would
   * be bound into the handlers for all asynchronous operations associated with
   * it. This works as follows:
   * 可以用shared_ptr來管理資源。當一個對象的生命期被綁定到一個連接或其他的異步操作,
   * shared_ptr管理的資源對象會被綁定到所有異步操作的處理句柄上。
   *
   * @li When a single connection ends, all associated asynchronous operations
   * complete. The corresponding handler objects are destroyed, and all
   * @c shared_ptr references to the objects are destroyed.
   * 當一個連接結束時,所有的異步操作完成。對應的處理句柄對象被銷燬,並且所有對這些對象的
   * shared_ptr的引用被銷燬。
   *
   * @li To shut down the whole program, the io_service function stop() is  
   * called to terminate any run() calls as soon as possible. The io_service
   * destructor defined above destroys all handlers, causing all @c shared_ptr
   * references to all connection objects to be destroyed.
   * 結束程序時,io_service的stop函數被調用,立即終結所有run函數。
   * io_service的析構會銷燬所有的句柄對象,並且所有對這些對象的shared_ptr的引用被銷燬。
   *
   */
  BOOST_ASIO_DECL ~io_service();

  /// Run the io_service object's event processing loop.
  /**
   * The run() function blocks until all work has finished and there are no
   * more handlers to be dispatched, or until the io_service has been stopped.
   * run函數會阻塞程序直到所有的工作已經完成,即沒有處理句柄需要去分發,或者
   * io_service被停止。
   *
   * Multiple threads may call the run() function to set up a pool of threads
   * from which the io_service may execute handlers. All threads that are
   * waiting in the pool are equivalent and the io_service may choose any one
   * of them to invoke a handler.
   * 多線程可以創建一個線程池,每個線程都去調用io_service的run函數來執行分發句柄。
   * 線程池中的線程平等的等待,並且io_service可以選擇其中的任何一個線程去喚醒句柄。
   *
   * A normal exit from the run() function implies that the io_service object
   * is stopped (the stopped() function returns @c true). Subsequent calls to
   * run(), run_one(), poll() or poll_one() will return immediately unless there
   * is a prior call to reset().
   * 如果stopped()返回值爲true,則run()正常退出,io_service服務已經停止,下一個調用
   * run、run_one、poll、poll_one等會立即返回,除非程序程序調用了具有優先調用權的reset函數。
   * reset函數會爲下次調用run函數做好準備。
   *
   * @return The number of handlers that were executed.
   * 返回執行的毀掉函數個數
   * 
   * @throws boost::system::system_error Thrown on failure.
   * 拋出 boost::system::system_error 如果出現錯誤。
   *
   * @note The run() function must not be called from a thread that is currently
   * calling one of run(), run_one(), poll() or poll_one() on the same
   * io_service object.
   * 如果一個進程正在調用io_service對象的run、run_one、poll、poll_one這些函數中的一個,那麼
   * 這個進程不能再次調用此io_service對象的run函數。
   *
   * The poll() function may also be used to dispatch ready handlers, but
   * without blocking.
   * poll函數也可以分發已經就緒的處理句柄,但是poll不會阻塞。
   */
  BOOST_ASIO_DECL std::size_t run();


  /// Run the io_service object's event processing loop.
  /**
   * The run() function blocks until all work has finished and there are no
   * more handlers to be dispatched, or until the io_service has been stopped.
   *
   * Multiple threads may call the run() function to set up a pool of threads
   * from which the io_service may execute handlers. All threads that are
   * waiting in the pool are equivalent and the io_service may choose any one
   * of them to invoke a handler.
   *
   * A normal exit from the run() function implies that the io_service object
   * is stopped (the stopped() function returns @c true). Subsequent calls to
   * run(), run_one(), poll() or poll_one() will return immediately unless there
   * is a prior call to reset().
   * 
   * @param ec Set to indicate what error occurred, if any.
   * 如果調用過程出現錯誤,ec參數會被設置,指出程序出現什麼錯誤。
   * 
   * @return The number of handlers that were executed.
   * 返回已經執行的處理句柄的個數。
   *
   * @note The run() function must not be called from a thread that is currently
   * calling one of run(), run_one(), poll() or poll_one() on the same
   * io_service object.
   *
   * The poll() function may also be used to dispatch ready handlers, but
   * without blocking.
   */
  BOOST_ASIO_DECL std::size_t run(boost::system::error_code& ec);

  /// Run the io_service object's event processing loop to execute at most one
  /// handler.
  /**
   * The run_one() function blocks until one handler has been dispatched, or
   * until the io_service has been stopped.
   * run_one函數會阻塞直到一個處理句柄被分發或者io_service已經停止
   *
   * @return The number of handlers that were executed. A zero return value
   * implies that the io_service object is stopped (the stopped() function
   * returns @c true). Subsequent calls to run(), run_one(), poll() or
   * poll_one() will return immediately unless there is a prior call to
   * reset().
   * 返回已經執行的處理句柄個數。返回值爲0說明io_service對象已經停止工作,下一個
   * 調用run、run_one、poll、poll_one會立即返回,除非調用了具有優先調用的reset函數。
   * reset函數會爲下次調用run函數做好準備。
   *
   * @throws boost::system::system_error Thrown on failure.
   * 如果調用出現錯誤, 拋出boost::systerm::systerm_error
   */
  BOOST_ASIO_DECL std::size_t run_one();

  /// Run the io_service object's event processing loop to execute at most one
  /// handler.
  /**
   * The run_one() function blocks until one handler has been dispatched, or
   * until the io_service has been stopped.
   *
   * @return The number of handlers that were executed. A zero return value
   * implies that the io_service object is stopped (the stopped() function
   * returns @c true). Subsequent calls to run(), run_one(), poll() or
   * poll_one() will return immediately unless there is a prior call to
   * reset().
   *
   * @return The number of handlers that were executed.
   * 
   */
  BOOST_ASIO_DECL std::size_t run_one(boost::system::error_code& ec);

  /// Run the io_service object's event processing loop to execute ready
  /// handlers.
  /**
   * The poll() function runs handlers that are ready to run, without blocking,
   * until the io_service has been stopped or there are no more ready handlers.
   * poll函數會運行已經準備好去執行的處理句柄,直到即沒有處理句柄需要去分發或者
   * io_service被停止。這個函數的調用時無阻塞的。
   * 
   * @return The number of handlers that were executed.
   * 返回已經執行的處理句柄的個數。
   *
   * @throws boost::system::system_error Thrown on failure.
   * 如果調用出現錯誤,會拋出boost::systerm::error
   *
   */
  BOOST_ASIO_DECL std::size_t poll();

  /// Run the io_service object's event processing loop to execute ready
  /// handlers.
  /**
   * The poll() function runs handlers that are ready to run, without blocking,
   * until the io_service has been stopped or there are no more ready handlers.
   *
   * @param ec Set to indicate what error occurred, if any.
   * 如果調用出現錯誤,參數ec會被設置,指出是什麼錯誤。
   *
   * @return The number of handlers that were executed.
   */
  BOOST_ASIO_DECL std::size_t poll(boost::system::error_code& ec);

  /// Run the io_service object's event processing loop to execute one ready
  /// handler.
  /**
   * The poll_one() function runs at most one handler that is ready to run,
   * without blocking.
   * poll_one函數最多運行一個準備執行的處理句柄,並且這個函數不會阻塞。
   *
   * @return The number of handlers that were executed.
   * 返回已經執行的處理句柄的個數
   *
   * @throws boost::system::system_error Thrown on failure.
   * 如果調用出現錯誤,會拋出boost::systerm::systerm_error
   * 
   */
  BOOST_ASIO_DECL std::size_t poll_one();

  /// Run the io_service object's event processing loop to execute one ready
  /// handler.
  /**
   * The poll_one() function runs at most one handler that is ready to run,
   * without blocking.
   *
   * @param ec Set to indicate what error occurred, if any.
   *
   * @return The number of handlers that were executed.
   */
  BOOST_ASIO_DECL std::size_t poll_one(boost::system::error_code& ec);

  /// Stop the io_service object's event processing loop.
  /**
   * This function does not block, but instead simply signals the io_service to
   * stop. All invocations of its run() or run_one() member functions should
   * return as soon as possible. Subsequent calls to run(), run_one(), poll()
   * or poll_one() will return immediately until reset() is called.
   * stop函數不會阻塞,而是發出信號通知io_service停止。所有run、run_one、poll、poll_one
   * 的調用會盡快返回。下一個調用run、run_one、poll、poll_one會立即返回,除非調用了具有
   * 優先調用的reset函數。reset函數會爲下次調用run函數做好準備。
   *
   */
  BOOST_ASIO_DECL void stop();

  /// Determine whether the io_service object has been stopped.
  /**
   * This function is used to determine whether an io_service object has been
   * stopped, either through an explicit call to stop(), or due to running out
   * of work. When an io_service object is stopped, calls to run(), run_one(),
   * poll() or poll_one() will return immediately without invoking any
   * handlers.
   * stopped函數可以判斷io_service對象是否已經停止,或者是通過顯式的調用stop,或者是
   * 完成所有的工作。如果io_service對象已經停止,所有調用run、run_one、poll、poll_one
   * 會立即返回,不會調用任何處理句柄。
   * @return @c true if the io_service object is stopped, otherwise @c false.
   */
  BOOST_ASIO_DECL bool stopped() const;

  /// Reset the io_service in preparation for a subsequent run() invocation.
  // 爲準備後續run函數的調用而重置io_service。
  /**
   * This function must be called prior to any second or later set of
   * invocations of the run(), run_one(), poll() or poll_one() functions when a
   * previous invocation of these functions returned due to the io_service
   * being stopped or running out of work. After a call to reset(), the
   * io_service object's stopped() function will return @c false.
   * 如果run、run_one、poll、poll_one這些函數由於io_service被停止或者完成任務而返回,
   * 我們想再次調用這些函數時,必須首先調用reset函數,再去調用前面的四個函數。調用reset
   * 函數後, stopped函數會返回false。
   *
   * This function must not be called while there are any unfinished calls to
   * the run(), run_one(), poll() or poll_one() functions.
   * 如果run、run_one、poll、poll_one這些函數中的任何一個沒有完成調用,reset函數就不能
   * 被調用,否則會出現未定義行爲。
   *
   */
  BOOST_ASIO_DECL void reset();

  /// Request the io_service to invoke the given handler.
  /**
   * This function is used to ask the io_service to execute the given handler.
   * dispatch函數請求io_service去執行一個給定的處理句柄。
   *
   * The io_service guarantees that the handler will only be called in a thread
   * in which the run(), run_one(), poll() or poll_one() member functions is
   * currently being invoked. The handler may be executed inside this function
   * if the guarantee can be met.
   * io_service保證這個處理句柄僅僅在一個進程中調用,這個進程正在調用run、run_one、poll、poll_one函數。
   * 如果滿足保證條件,這個句柄會在dispatch這個函數中調用。
   *
   * @param handler The handler to be called. The io_service will make
   * a copy of the handler object as required. The function signature of the
   * handler must be: @code void handler(); @endcode
   * 參數handler是一個被調用的處理句柄,其函數簽名必須是void(void)。io_service會複製
   * handler對象。
   *
   * @note This function throws an exception only if:
   * @li the handler's @c asio_handler_allocate function; or
   * @li the handler's copy constructor
   * throws an exception.
   * 注意:這個函數只會在asio_handler_allocate函數或handler的拷貝構造函數中拋出異常。
   *
   */
  template <typename CompletionHandler>
  BOOST_ASIO_INITFN_RESULT_TYPE(CompletionHandler, void ())
  dispatch(BOOST_ASIO_MOVE_ARG(CompletionHandler) handler);


  /// Request the io_service to invoke the given handler and return immediately.
  /// 請求io_service去執行一個給定的處理句柄並立即返回。
  /**
   * This function is used to ask the io_service to execute the given handler,
   * but without allowing the io_service to call the handler from inside this
   * function.
   * post函數請求io_service去執行一個給定的處理句柄,但是不允許io_service在這個
   * 函數中調用處理句柄。
   *
   * The io_service guarantees that the handler will only be called in a thread
   * in which the run(), run_one(), poll() or poll_one() member functions is
   * currently being invoked.
   * io_service保證這個處理句柄僅僅在一個進程中調用,這個進程正在調用run、run_one、
   * poll、poll_one函數。
   *
   * @param handler The handler to be called. The io_service will make
   * a copy of the handler object as required. The function signature of the
   * handler must be: @code void handler(); @endcode
   * 參數handler是一個被調用的處理句柄,其函數簽名必須是void(void)。io_service會複製
   * handler對象。
   *
   * @note This function throws an exception only if:
   * @li the handler's @c asio_handler_allocate function; or
   * @li the handler's copy constructor
   * throws an exception.
   * 注意:這個函數只會在asio_handler_allocate函數或handler的拷貝構造函數中拋出異常。
   *
   */
  template <typename CompletionHandler>
  BOOST_ASIO_INITFN_RESULT_TYPE(CompletionHandler, void ())
  post(BOOST_ASIO_MOVE_ARG(CompletionHandler) handler);


  /// Create a new handler that automatically dispatches the wrapped handler
  /// on the io_service.
  /// 創建一個新句柄,並自動的分發這個被包裝的句柄。
  /**
   * This function is used to create a new handler function object that, when
   * invoked, will automatically pass the wrapped handler to the io_service
   * object's dispatch function.
   * wrap函數創建一個新的句柄對象,在調用時,會自動的把這個被包裝的句柄傳遞給io_service的dispatch函數
   * 注:這裏好像有錯誤,需要調用wrapped_handler的重載操作符(),不然這個句柄就不會被調用。
   *
   * @param handler The handler to be wrapped. The io_service will make a copy
   * of the handler object as required. The function signature of the handler
   * must be: @code void handler(A1 a1, ... An an); @endcode
   * 參數handler是被包裝的句柄,io_service會複製handler對象,handler的函數簽名必須
   * 是void handler(A1 a1, ... An an)
   *
   * @return A function object that, when invoked, passes the wrapped handler to
   * the io_service object's dispatch function. Given a function object with the
   * signature:
   * @code R f(A1 a1, ... An an); @endcode
   * If this function object is passed to the wrap function like so:
   * @code io_service.wrap(f); @endcode
   * then the return value is a function object with the signature
   * @code void g(A1 a1, ... An an); @endcode
   * that, when invoked, executes code equivalent to:
   * @code io_service.dispatch(boost::bind(f, a1, ... an)); @endcode
   * 返回一個函數對象,當調用時,把這個包裝過得處理句柄傳遞給io_service的dispatch函數。
   * 給一個函數對象其簽名是R f(A1 a1, ...An an);
   * 當執行:io_service.wrap(f)時
   * 返回一個函數對象g,其函數簽名是:void g(A1 a1, ...An an)
   * 當被調用時,等於執行如下代碼:io_service.dispatch(boost::bind(f, a1, ... an));
   * 
   */
  template <typename Handler>
#if defined(GENERATING_DOCUMENTATION)
  unspecified
#else
  detail::wrapped_handler<io_service&, Handler>
#endif
  wrap(Handler handler);


  /// Fork-related event notifications.
  ///fork事件相關的通知
  enum fork_event
  {
    /// Notify the io_service that the process is about to fork.
    fork_prepare,


    /// Notify the io_service that the process has forked and is the parent.
    fork_parent,  


    /// Notify the io_service that the process has forked and is the child.
    fork_child
  };

  /// Notify the io_service of a fork-related event.
  /**
   * This function is used to inform the io_service that the process is about
   * to fork, or has just forked. This allows the io_service, and the services
   * it contains, to perform any necessary housekeeping to ensure correct
   * operation following a fork.
   *
   * This function must not be called while any other io_service function, or
   * any function on an I/O object associated with the io_service, is being
   * called in another thread. It is, however, safe to call this function from
   * within a completion handler, provided no other thread is accessing the
   * io_service.
   *
   * @param event A fork-related event.
   *
   * @throws boost::system::system_error Thrown on failure. If the notification
   * fails the io_service object should no longer be used and should be
   * destroyed.
   *
   * @par Example
   * The following code illustrates how to incorporate the notify_fork()
   * function:
   * @code my_io_service.notify_fork(boost::asio::io_service::fork_prepare);
   * if (fork() == 0)
   * {
   *   // This is the child process.
   *   my_io_service.notify_fork(boost::asio::io_service::fork_child);
   * }
   * else
   * {
   *   // This is the parent process.
   *   my_io_service.notify_fork(boost::asio::io_service::fork_parent);
   * } @endcode
   *
   * @note For each service object @c svc in the io_service set, performs
   * <tt>svc->fork_service();</tt>. When processing the fork_prepare event,
   * services are visited in reverse order of the beginning of service object
   * lifetime. Otherwise, services are visited in order of the beginning of
   * service object lifetime.
   */
  BOOST_ASIO_DECL void notify_fork(boost::asio::io_service::fork_event event);

  /// Obtain the service object corresponding to the given type.
  /**
   * This function is used to locate a service object that corresponds to
   * the given service type. If there is no existing implementation of the
   * service, then the io_service will create a new instance of the service.
   *
   * @param ios The io_service object that owns the service.
   *
   * @return The service interface implementing the specified service type.
   * Ownership of the service interface is not transferred to the caller.
   * particular service with the function template @c has_service<Service>().
   * 通過調用use_service,類型參數選擇一個Service,這種類型的所有成員就可以使用了。
   * 如果Service不在一個io_service,就會創建一個type的Service,並把這個Service加入到io_service。
   * 在c++程序中,我們可以用has_service來檢查一個io_service對象是否存在一個特殊的service。
   *
   */
  template <typename Service>
  friend Service& use_service(io_service& ios);


  /// Add a service object to the io_service.
  /**
   * This function is used to add a service to the io_service.
   * add_service函數:在io_service增加一個servcie
   *
   * @param ios The io_service object that owns the service.
   * 參數ios對象擁有這個service
   *
   * @param svc The service object. On success, ownership of the service object
   * is transferred to the io_service. When the io_service object is destroyed,
   * it will destroy the service object by performing:
   * @code delete static_cast<io_service::service*>(svc) @endcode
   *
   * @throws boost::asio::service_already_exists Thrown if a service of the
   * given type is already present in the io_service.
   *
   * @throws boost::asio::invalid_service_owner Thrown if the service's owning
   * io_service is not the io_service object specified by the ios parameter.
   * Service 對象可以通過add_service加入io_service對象中,加入這個Service對象已經存在,
   * 會拋出一個service已經存在的異常。 如果service的擁有者不和參數io_service是同一個對象,
   * 會拋出無效的service擁有者的異常。
   *
   */
  template <typename Service>
  friend void add_service(io_service& ios, Service* svc);


  /// Determine if an io_service contains a specified service type.
  /**
   * This function is used to determine whether the io_service contains a
   * service object corresponding to the given service type.
   *
   * @param ios The io_service object that owns the service.
   *
   * @return A boolean indicating whether the io_service contains the service.
   */
  template <typename Service>
  friend bool has_service(io_service& ios);


private:
#if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
  detail::winsock_init<> init_;
#elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \
  || defined(__osf__)
  detail::signal_init<> init_;
#endif

  // The service registry.
  boost::asio::detail::service_registry* service_registry_;

  // The implementation.
  impl_type& impl_;
};

http://blog.csdn.net/xiaoliangsky/article/details/43125525


測試用例

test_io_service.h

boost::mutex g_mutex;

template<int N>
struct print_n_msg
{
	typedef void result_type;

	void operator()(const std::string& msg, int flag)
	{
		boost::mutex::scoped_lock lock(g_mutex);
		std::cout << "thread: [" << boost::this_thread::get_id() << "] the num: " << N << " the message is: " << msg << std::endl;
	}

	void operator()(unsigned int milliseconds,  int flag)
	{
		{
			boost::mutex::scoped_lock lock(g_mutex);
			std::cout << "thread: [" << boost::this_thread::get_id() << "] sleep begin; the num is: " << N << std::endl;
		}

		boost::this_thread::sleep(boost::posix_time::milliseconds(milliseconds));

		{
			boost::mutex::scoped_lock lock(g_mutex);
			std::cout << "thread: [" << boost::this_thread::get_id() << "] sleep over." << N << std::endl;;
		}
	}

	void print(const std::string& msg)
	{
		boost::mutex::scoped_lock lock(g_mutex);
		std::cout << "thread: [" << boost::this_thread::get_id() << "] the num: " << N << " the message is: " << msg << std::endl;
	}

	void operator()(const boost::system::error_code& error)
	{
		if (!error)
		{
			boost::mutex::scoped_lock lock(g_mutex);
			std::cout << "thread: [" << boost::this_thread::get_id() << "] the num is: " << N << ", no error," << std::endl;
		}
		else
		{
			boost::mutex::scoped_lock lock(g_mutex);
			std::cout << __FUNCTION__ << " the num is :" << N << " occur a error : " << error.message() << std::endl;
		}
	}
};

void test_dispatch()
{
	boost::asio::io_service     io;
	boost::asio::deadline_timer t(io);
	t.expires_from_now(boost::posix_time::seconds(2));
	t.async_wait(print_n_msg<1>());

	io.dispatch(boost::bind(print_n_msg<2>(), "dispatch is testing", 1));
	io.dispatch(boost::bind(print_n_msg<3>(), 500, 1));

	io.run();
}

void bind_run(boost::asio::io_service* io)
{
	{
		boost::mutex::scoped_lock lock(g_mutex);
		std::cout << "thread {{" << boost::this_thread::get_id() << "}} run begin;" << std::endl;
	}

	size_t rh = io->run();

	{
		boost::mutex::scoped_lock lock(g_mutex);
		std::cout << "thread {{" << boost::this_thread::get_id() << "}} run over;"
			<< "the handler number is " << rh << std::endl;
	}
}

void test_post()
{
	boost::asio::io_service     io;
	boost::asio::deadline_timer t(io);
	t.expires_from_now(boost::posix_time::milliseconds(1));
	t.async_wait(boost::bind(print_n_msg<4>(), "wait 4 is finish", 1));
	t.async_wait(boost::bind(print_n_msg<5>(), "wait 5 is finish", 1));
	t.async_wait(boost::bind(print_n_msg<6>(), "wait 6 is finish", 1));

	io.post(boost::bind(print_n_msg<7>(), "post 7 is posted", 1));
	io.post(boost::bind(print_n_msg<8>(), "post 8 is posted", 1));
	io.post(boost::bind(print_n_msg<9>(), 1, 1));
	io.post(boost::bind(print_n_msg<10>(), "post 10 is posted", 1));
	io.post(boost::bind(print_n_msg<11>(), 1, 1));
	io.post(boost::bind(print_n_msg<12>(), "post 12 is posted", 1));
	io.post(boost::bind(print_n_msg<13>(), "post 13 is posted", 1));

	boost::thread_group tg;
	tg.create_thread(boost::bind(bind_run, &io));
	tg.create_thread(boost::bind(bind_run, &io));

	tg.join_all();

	if (io.stopped())
	{
		io.reset();
		io.post(boost::bind(print_n_msg<14>(), "post 14 is posted", 1));
		io.post(boost::bind(print_n_msg<15>(), "post 15 is posted", 1));
		io.wrap(boost::bind(print_n_msg<16>(), "post 16 is posted", 1));

		io.run();

		if (io.stopped())
		{
			std::cout << "io service is stopped" << std::endl;
		}
		else
		{
			std::cout << "no" << std::endl;
		}
	}
}

void bind_poll(boost::asio::io_service* io)
{
	{
		boost::mutex::scoped_lock lock(g_mutex);
		std::cout << "thread {{" << boost::this_thread::get_id() << "}} poll begin;" << std::endl;
	}

	size_t rh = io->poll();

	{
		boost::mutex::scoped_lock lock(g_mutex);
		std::cout << "thread {{" << boost::this_thread::get_id() << "}} poll over;"
			<< "the handler number is " << rh << std::endl;
	}
}

void test_poll()
{
	boost::asio::io_service     io;
	boost::asio::deadline_timer t(io);
	t.expires_from_now(boost::posix_time::milliseconds(1));
	t.async_wait(boost::bind(print_n_msg<4>(), "wait 4 is finish", 1));
	t.async_wait(boost::bind(print_n_msg<5>(), "wait 5 is finish", 1));
	t.async_wait(boost::bind(print_n_msg<6>(), "wait 6 is finish", 1));

	io.post(boost::bind(print_n_msg<7>(), "post 7 is posted", 1));
	io.post(boost::bind(print_n_msg<8>(), "post 8 is posted", 1));
	io.post(boost::bind(print_n_msg<9>(), 1, 1));
	io.post(boost::bind(print_n_msg<10>(), "post 10 is posted", 1));
	io.post(boost::bind(print_n_msg<11>(), 1, 1));
	io.post(boost::bind(print_n_msg<12>(), "post 12 is posted", 1));
	io.post(boost::bind(print_n_msg<13>(), "post 13 is posted", 1));

	boost::thread_group tg;

	tg.create_thread(boost::bind(bind_poll, &io));
	tg.create_thread(boost::bind(bind_poll, &io));

	tg.join_all();

	if (io.stopped())
	{
		io.reset();
		io.post(boost::bind(print_n_msg<14>(), "post 14 is posted", 1));
		io.post(boost::bind(print_n_msg<15>(), "post 15 is posted", 1));

		io.poll();

		if (io.stopped())
		{
			std::cout << "io service is stopped" << std::endl;
		}
		else
		{
			std::cout << "no" << std::endl;
		}
	}
}

//#include <boost/asio/detail/wrapped_handler.hpp>

void test_poll_one()
{
	boost::asio::io_service     io;

	io.post(boost::bind(print_n_msg<7>(), "post 7 is posted", 1));
	io.post(boost::bind(print_n_msg<8>(), "post 8 is posted", 1));

	io.poll_one();

	if (io.stopped())
	{
		std::cout << "io_service has stopped" << std::endl;
	}
	else
	{
		std::cout << "no" << std::endl;
		io.poll_one();

		if (io.stopped()) 
		{
			std::cout << "reset" << std::endl;
			io.reset();//這裏需要重新啓動
			boost::function<void(void)> fun = boost::bind(print_n_msg<9>(), "post 9 is posted", 1);
			boost::asio::detail::wrapped_handler<boost::asio::io_service&, boost::function<void(void)>>
				handler = io.wrap(fun);

			handler();//需要自己調用才能執行handler。
			io.poll_one();
		}
	}
}
main.cpp

#include "test_io_service.h"

void testIOS()
{
	//using namespace stmlIOS;
	//test_dispatch();
	//test_post();
	//std::cout << "\n\n";
	//test_poll();

	test_poll_one();
}

int main()
{
	testIOS();

	system("pause");

	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章