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: [email protected]

* @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;
}
时间: 2025-01-18 17:52:24

boost::asio::io_service(之一)的相关文章

Boost::asio io_service 实现分析

io_service的作用 io_servie 实现了一个任务队列,这里的任务就是void(void)的函数.Io_servie最常用的两个接口是post和run,post向任务队列中投递任务,run是执行队列中的任务,直到全部执行完毕,并且run可以被N个线程调用.Io_service是完全线程安全的队列. Io_servie的接口 提供的接口有run.run_one.poll.poll_one.stop.reset.dispatch.post,最常用的是run.post.stop Io_se

boost asio io_service学习笔记

构造函数 构造函数的主要动作就是调用CreateIoCompletionPort创建了一个初始iocp. Dispatch和post的区别 Post一定是PostQueuedCompletionStatus并且在GetQueuedCompletionStatus 之后执行. Dispatch会首先检查当前thread是不是io_service.run/runonce/poll/poll_once线程,如果是,则直接运行. poll和run的区别 两者代码几乎一样,都是首先检查是否有outstan

boost::asio::io_service 超时设置

class client{public:  /*client(const udp::endpoint& listen_endpoint)    : socket_(io_service_, listen_endpoint),      deadline_(io_service_)  {    deadline_.expires_at(boost::posix_time::pos_infin);    check_deadline();  } std::size_t receive(const b

boost::asio的io_service处理过程

1.主线程定义回调对象 2.调用io object的操作 3.io object会另开线程,定义opertion op来执行操作,同时将回调对象加到op的do_complete上.进行操作 4.完成操作加入完成队列 5.io_service线程循环从完成队列取事件,调用其事件对应的回调函数 Operation 还记得前面我们在分析resolver的实现的时候,挖了一个关于operation的坑?为了不让自己陷进去,现在来填吧:接下来我们就来看看asio中的各种operation. 和前面提到过的

Boost.ASIO简要分析-5 多io_service

5. 多io_service 前面那篇讲到了多线程的用法.这篇讲一下多io_service的用法,大家可参考下官方提供的HTTP Server 2(an io_service-per-CPU)这个例子. 官方提供的例子中,使用方法很简单,建立一个io_service_pool,然后对每一个io_service开一个线程去让它跑起来(毕竟,io_service::run这个函数在有任务的时候会一直工作的,只有开多个线程才做到不影响别的io_service).当然,我们也可以为每个io_servic

boost.asio系列——io_service

IO模型 io_service对象是asio框架中的调度器,所有异步io事件都是通过它来分发处理的(io对象的构造函数中都需要传入一个io_service对象). asio::io_service io_service;    asio::ip::tcp::socket socket(io_service); 在asio框架中,同步的io主要流程如下: 应用程序调用IO对象成员函数执行IO操作 IO对象向io_service 提出请求. io_service 调用操作系统的功能执行连接操作. 操

10 C++ Boost ASIO网路通信库 TCP/UDP,HTTP

  tcp 同步服务器,显示服务器端时间 tcp 同步服务器,提供多种选择 多线程的tcp 同步服务器 tcp 同步客户端 boost 域名地址解析 tcp异步服务器 tcp 异步客户端 UDP同步服务器 UDP同步客户端 UDP异步服务器 UDP异步客户端 HTTP同步客户端 HTTP异步客户端 同步实验: 异步实验 多线程异步实验 tcp 同步服务器,显示服务器端时间 [email protected]:~/boost$ cat main.cpp  #include <ctime> #in

C/C++利用Boost::Asio网络库建立自己的Socket服务器

引言 寸光阴,当下我们或许更需要利用现有的知识,应用现有的技术.网络是当前互联网的根本,了解网络便开始显得极其重要.今天我们利用Boost库中Asio部分,浅尝网络服务器.此处不做过于深入的开展,为达成学习目的,只做简单的异步并发服务器. 注意:本篇代码没有直接引用boost等命名空间,为的是新入门Boost的同学能够更好的了解每个参数在boost的具体命名空间位置,有助于更好的理解boost的布局. 版权所有:_OE_,转载请注明出处:http://blog.csdn.net/csnd_ayo

boost asio异步读写网络聊天程序客户端 实例详解

// // chat_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2013 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://ww