io_service.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. //
  2. // io_service.hpp
  3. // ~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef ASIO_IO_SERVICE_HPP
  11. #define ASIO_IO_SERVICE_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/push_options.hpp"
  16. #include "asio/detail/push_options.hpp"
  17. #include <cstddef>
  18. #include <stdexcept>
  19. #include <typeinfo>
  20. #include <boost/config.hpp>
  21. #include <boost/throw_exception.hpp>
  22. #include "asio/detail/pop_options.hpp"
  23. #include "asio/error_code.hpp"
  24. #include "asio/detail/noncopyable.hpp"
  25. #include "asio/detail/reactor_fwd.hpp"
  26. #include "asio/detail/service_registry_fwd.hpp"
  27. #include "asio/detail/signal_init.hpp"
  28. #include "asio/detail/task_io_service_fwd.hpp"
  29. #include "asio/detail/win_iocp_io_service_fwd.hpp"
  30. #include "asio/detail/winsock_init.hpp"
  31. #include "asio/detail/wrapped_handler.hpp"
  32. namespace asio {
  33. class io_service;
  34. template <typename Service> Service& use_service(io_service& ios);
  35. template <typename Service> void add_service(io_service& ios, Service* svc);
  36. template <typename Service> bool has_service(io_service& ios);
  37. #if defined(ASIO_HAS_IOCP)
  38. namespace detail { typedef win_iocp_io_service io_service_impl; }
  39. #else
  40. namespace detail { typedef task_io_service<reactor> io_service_impl; }
  41. #endif
  42. /// Provides core I/O functionality.
  43. /**
  44. * The io_service class provides the core I/O functionality for users of the
  45. * asynchronous I/O objects, including:
  46. *
  47. * @li asio::ip::tcp::socket
  48. * @li asio::ip::tcp::acceptor
  49. * @li asio::ip::udp::socket
  50. * @li asio::deadline_timer.
  51. *
  52. * The io_service class also includes facilities intended for developers of
  53. * custom asynchronous services.
  54. *
  55. * @par Thread Safety
  56. * @e Distinct @e objects: Safe.@n
  57. * @e Shared @e objects: Safe, with the exception that calling reset() while
  58. * there are unfinished run(), run_one(), poll() or poll_one() calls results in
  59. * undefined behaviour.
  60. *
  61. * @par Concepts:
  62. * Dispatcher.
  63. *
  64. * @par Synchronous and asynchronous operations
  65. *
  66. * Synchronous operations on I/O objects implicitly run the io_service object
  67. * for an individual operation. The io_service functions run(), run_one(),
  68. * poll() or poll_one() must be called for the io_service to perform
  69. * asynchronous operations on behalf of a C++ program. Notification that an
  70. * asynchronous operation has completed is delivered by invocation of the
  71. * associated handler. Handlers are invoked only by a thread that is currently
  72. * calling any overload of run(), run_one(), poll() or poll_one() for the
  73. * io_service.
  74. *
  75. * @par Effect of exceptions thrown from handlers
  76. *
  77. * If an exception is thrown from a handler, the exception is allowed to
  78. * propagate through the throwing thread's invocation of run(), run_one(),
  79. * poll() or poll_one(). No other threads that are calling any of these
  80. * functions are affected. It is then the responsibility of the application to
  81. * catch the exception.
  82. *
  83. * After the exception has been caught, the run(), run_one(), poll() or
  84. * poll_one() call may be restarted @em without the need for an intervening
  85. * call to reset(). This allows the thread to rejoin the io_service object's
  86. * thread pool without impacting any other threads in the pool.
  87. *
  88. * For example:
  89. *
  90. * @code
  91. * asio::io_service io_service;
  92. * ...
  93. * for (;;)
  94. * {
  95. * try
  96. * {
  97. * io_service.run();
  98. * break; // run() exited normally
  99. * }
  100. * catch (my_exception& e)
  101. * {
  102. * // Deal with exception as appropriate.
  103. * }
  104. * }
  105. * @endcode
  106. *
  107. * @par Stopping the io_service from running out of work
  108. *
  109. * Some applications may need to prevent an io_service object's run() call from
  110. * returning when there is no more work to do. For example, the io_service may
  111. * be being run in a background thread that is launched prior to the
  112. * application's asynchronous operations. The run() call may be kept running by
  113. * creating an object of type asio::io_service::work:
  114. *
  115. * @code asio::io_service io_service;
  116. * asio::io_service::work work(io_service);
  117. * ... @endcode
  118. *
  119. * To effect a shutdown, the application will then need to call the io_service
  120. * object's stop() member function. This will cause the io_service run() call
  121. * to return as soon as possible, abandoning unfinished operations and without
  122. * permitting ready handlers to be dispatched.
  123. *
  124. * Alternatively, if the application requires that all operations and handlers
  125. * be allowed to finish normally, the work object may be explicitly destroyed.
  126. *
  127. * @code asio::io_service io_service;
  128. * auto_ptr<asio::io_service::work> work(
  129. * new asio::io_service::work(io_service));
  130. * ...
  131. * work.reset(); // Allow run() to exit. @endcode
  132. *
  133. * @par The io_service class and I/O services
  134. *
  135. * Class io_service implements an extensible, type-safe, polymorphic set of I/O
  136. * services, indexed by service type. An object of class io_service must be
  137. * initialised before I/O objects such as sockets, resolvers and timers can be
  138. * used. These I/O objects are distinguished by having constructors that accept
  139. * an @c io_service& parameter.
  140. *
  141. * I/O services exist to manage the logical interface to the operating system on
  142. * behalf of the I/O objects. In particular, there are resources that are shared
  143. * across a class of I/O objects. For example, timers may be implemented in
  144. * terms of a single timer queue. The I/O services manage these shared
  145. * resources.
  146. *
  147. * Access to the services of an io_service is via three function templates,
  148. * use_service(), add_service() and has_service().
  149. *
  150. * In a call to @c use_service<Service>(), the type argument chooses a service,
  151. * making available all members of the named type. If @c Service is not present
  152. * in an io_service, an object of type @c Service is created and added to the
  153. * io_service. A C++ program can check if an io_service implements a
  154. * particular service with the function template @c has_service<Service>().
  155. *
  156. * Service objects may be explicitly added to an io_service using the function
  157. * template @c add_service<Service>(). If the @c Service is already present, the
  158. * service_already_exists exception is thrown. If the owner of the service is
  159. * not the same object as the io_service parameter, the invalid_service_owner
  160. * exception is thrown.
  161. *
  162. * Once a service reference is obtained from an io_service object by calling
  163. * use_service(), that reference remains usable as long as the owning io_service
  164. * object exists.
  165. *
  166. * All I/O service implementations have io_service::service as a public base
  167. * class. Custom I/O services may be implemented by deriving from this class and
  168. * then added to an io_service using the facilities described above.
  169. */
  170. class io_service
  171. : private noncopyable
  172. {
  173. private:
  174. typedef detail::io_service_impl impl_type;
  175. #if defined(ASIO_HAS_IOCP)
  176. friend class detail::win_iocp_overlapped_ptr;
  177. #endif
  178. public:
  179. class work;
  180. friend class work;
  181. class id;
  182. class service;
  183. class strand;
  184. /// Constructor.
  185. io_service();
  186. /// Constructor.
  187. /**
  188. * Construct with a hint about the required level of concurrency.
  189. *
  190. * @param concurrency_hint A suggestion to the implementation on how many
  191. * threads it should allow to run simultaneously.
  192. */
  193. explicit io_service(std::size_t concurrency_hint);
  194. /// Destructor.
  195. /**
  196. * On destruction, the io_service performs the following sequence of
  197. * operations:
  198. *
  199. * @li For each service object @c svc in the io_service set, in reverse order
  200. * of the beginning of service object lifetime, performs
  201. * @c svc->shutdown_service().
  202. *
  203. * @li Uninvoked handler objects that were scheduled for deferred invocation
  204. * on the io_service, or any associated strand, are destroyed.
  205. *
  206. * @li For each service object @c svc in the io_service set, in reverse order
  207. * of the beginning of service object lifetime, performs
  208. * <tt>delete static_cast<io_service::service*>(svc)</tt>.
  209. *
  210. * @note The destruction sequence described above permits programs to
  211. * simplify their resource management by using @c shared_ptr<>. Where an
  212. * object's lifetime is tied to the lifetime of a connection (or some other
  213. * sequence of asynchronous operations), a @c shared_ptr to the object would
  214. * be bound into the handlers for all asynchronous operations associated with
  215. * it. This works as follows:
  216. *
  217. * @li When a single connection ends, all associated asynchronous operations
  218. * complete. The corresponding handler objects are destroyed, and all
  219. * @c shared_ptr references to the objects are destroyed.
  220. *
  221. * @li To shut down the whole program, the io_service function stop() is
  222. * called to terminate any run() calls as soon as possible. The io_service
  223. * destructor defined above destroys all handlers, causing all @c shared_ptr
  224. * references to all connection objects to be destroyed.
  225. */
  226. ~io_service();
  227. /// Run the io_service object's event processing loop.
  228. /**
  229. * The run() function blocks until all work has finished and there are no
  230. * more handlers to be dispatched, or until the io_service has been stopped.
  231. *
  232. * Multiple threads may call the run() function to set up a pool of threads
  233. * from which the io_service may execute handlers. All threads that are
  234. * waiting in the pool are equivalent and the io_service may choose any one
  235. * of them to invoke a handler.
  236. *
  237. * The run() function may be safely called again once it has completed only
  238. * after a call to reset().
  239. *
  240. * @return The number of handlers that were executed.
  241. *
  242. * @throws asio::system_error Thrown on failure.
  243. *
  244. * @note The run() function must not be called from a thread that is currently
  245. * calling one of run(), run_one(), poll() or poll_one() on the same
  246. * io_service object.
  247. *
  248. * The poll() function may also be used to dispatch ready handlers, but
  249. * without blocking.
  250. */
  251. std::size_t run();
  252. /// Run the io_service object's event processing loop.
  253. /**
  254. * The run() function blocks until all work has finished and there are no
  255. * more handlers to be dispatched, or until the io_service has been stopped.
  256. *
  257. * Multiple threads may call the run() function to set up a pool of threads
  258. * from which the io_service may execute handlers. All threads that are
  259. * waiting in the pool are equivalent and the io_service may choose any one
  260. * of them to invoke a handler.
  261. *
  262. * The run() function may be safely called again once it has completed only
  263. * after a call to reset().
  264. *
  265. * @param ec Set to indicate what error occurred, if any.
  266. *
  267. * @return The number of handlers that were executed.
  268. *
  269. * @note The run() function must not be called from a thread that is currently
  270. * calling one of run(), run_one(), poll() or poll_one() on the same
  271. * io_service object.
  272. *
  273. * The poll() function may also be used to dispatch ready handlers, but
  274. * without blocking.
  275. */
  276. std::size_t run(asio::error_code& ec);
  277. /// Run the io_service object's event processing loop to execute at most one
  278. /// handler.
  279. /**
  280. * The run_one() function blocks until one handler has been dispatched, or
  281. * until the io_service has been stopped.
  282. *
  283. * @return The number of handlers that were executed.
  284. *
  285. * @throws asio::system_error Thrown on failure.
  286. */
  287. std::size_t run_one();
  288. /// Run the io_service object's event processing loop to execute at most one
  289. /// handler.
  290. /**
  291. * The run_one() function blocks until one handler has been dispatched, or
  292. * until the io_service has been stopped.
  293. *
  294. * @param ec Set to indicate what error occurred, if any.
  295. *
  296. * @return The number of handlers that were executed.
  297. */
  298. std::size_t run_one(asio::error_code& ec);
  299. /// Run the io_service object's event processing loop to execute ready
  300. /// handlers.
  301. /**
  302. * The poll() function runs handlers that are ready to run, without blocking,
  303. * until the io_service has been stopped or there are no more ready handlers.
  304. *
  305. * @return The number of handlers that were executed.
  306. *
  307. * @throws asio::system_error Thrown on failure.
  308. */
  309. std::size_t poll();
  310. /// Run the io_service object's event processing loop to execute ready
  311. /// handlers.
  312. /**
  313. * The poll() function runs handlers that are ready to run, without blocking,
  314. * until the io_service has been stopped or there are no more ready handlers.
  315. *
  316. * @param ec Set to indicate what error occurred, if any.
  317. *
  318. * @return The number of handlers that were executed.
  319. */
  320. std::size_t poll(asio::error_code& ec);
  321. /// Run the io_service object's event processing loop to execute one ready
  322. /// handler.
  323. /**
  324. * The poll_one() function runs at most one handler that is ready to run,
  325. * without blocking.
  326. *
  327. * @return The number of handlers that were executed.
  328. *
  329. * @throws asio::system_error Thrown on failure.
  330. */
  331. std::size_t poll_one();
  332. /// Run the io_service object's event processing loop to execute one ready
  333. /// handler.
  334. /**
  335. * The poll_one() function runs at most one handler that is ready to run,
  336. * without blocking.
  337. *
  338. * @param ec Set to indicate what error occurred, if any.
  339. *
  340. * @return The number of handlers that were executed.
  341. */
  342. std::size_t poll_one(asio::error_code& ec);
  343. /// Stop the io_service object's event processing loop.
  344. /**
  345. * This function does not block, but instead simply signals the io_service to
  346. * stop. All invocations of its run() or run_one() member functions should
  347. * return as soon as possible. Subsequent calls to run(), run_one(), poll()
  348. * or poll_one() will return immediately until reset() is called.
  349. */
  350. void stop();
  351. /// Reset the io_service in preparation for a subsequent run() invocation.
  352. /**
  353. * This function must be called prior to any second or later set of
  354. * invocations of the run(), run_one(), poll() or poll_one() functions when a
  355. * previous invocation of these functions returned due to the io_service
  356. * being stopped or running out of work. This function allows the io_service
  357. * to reset any internal state, such as a "stopped" flag.
  358. *
  359. * This function must not be called while there are any unfinished calls to
  360. * the run(), run_one(), poll() or poll_one() functions.
  361. */
  362. void reset();
  363. /// Request the io_service to invoke the given handler.
  364. /**
  365. * This function is used to ask the io_service to execute the given handler.
  366. *
  367. * The io_service guarantees that the handler will only be called in a thread
  368. * in which the run(), run_one(), poll() or poll_one() member functions is
  369. * currently being invoked. The handler may be executed inside this function
  370. * if the guarantee can be met.
  371. *
  372. * @param handler The handler to be called. The io_service will make
  373. * a copy of the handler object as required. The function signature of the
  374. * handler must be: @code void handler(); @endcode
  375. *
  376. * @note This function throws an exception only if:
  377. *
  378. * @li the handler's @c asio_handler_allocate function; or
  379. *
  380. * @li the handler's copy constructor
  381. *
  382. * throws an exception.
  383. */
  384. template <typename CompletionHandler>
  385. void dispatch(CompletionHandler handler);
  386. /// Request the io_service to invoke the given handler and return immediately.
  387. /**
  388. * This function is used to ask the io_service to execute the given handler,
  389. * but without allowing the io_service to call the handler from inside this
  390. * function.
  391. *
  392. * The io_service guarantees that the handler will only be called in a thread
  393. * in which the run(), run_one(), poll() or poll_one() member functions is
  394. * currently being invoked.
  395. *
  396. * @param handler The handler to be called. The io_service will make
  397. * a copy of the handler object as required. The function signature of the
  398. * handler must be: @code void handler(); @endcode
  399. *
  400. * @note This function throws an exception only if:
  401. *
  402. * @li the handler's @c asio_handler_allocate function; or
  403. *
  404. * @li the handler's copy constructor
  405. *
  406. * throws an exception.
  407. */
  408. template <typename CompletionHandler>
  409. void post(CompletionHandler handler);
  410. /// Create a new handler that automatically dispatches the wrapped handler
  411. /// on the io_service.
  412. /**
  413. * This function is used to create a new handler function object that, when
  414. * invoked, will automatically pass the wrapped handler to the io_service
  415. * object's dispatch function.
  416. *
  417. * @param handler The handler to be wrapped. The io_service will make a copy
  418. * of the handler object as required. The function signature of the handler
  419. * must be: @code void handler(A1 a1, ... An an); @endcode
  420. *
  421. * @return A function object that, when invoked, passes the wrapped handler to
  422. * the io_service object's dispatch function. Given a function object with the
  423. * signature:
  424. * @code R f(A1 a1, ... An an); @endcode
  425. * If this function object is passed to the wrap function like so:
  426. * @code io_service.wrap(f); @endcode
  427. * then the return value is a function object with the signature
  428. * @code void g(A1 a1, ... An an); @endcode
  429. * that, when invoked, executes code equivalent to:
  430. * @code io_service.dispatch(boost::bind(f, a1, ... an)); @endcode
  431. */
  432. template <typename Handler>
  433. #if defined(GENERATING_DOCUMENTATION)
  434. unspecified
  435. #else
  436. detail::wrapped_handler<io_service&, Handler>
  437. #endif
  438. wrap(Handler handler);
  439. /// Obtain the service object corresponding to the given type.
  440. /**
  441. * This function is used to locate a service object that corresponds to
  442. * the given service type. If there is no existing implementation of the
  443. * service, then the io_service will create a new instance of the service.
  444. *
  445. * @param ios The io_service object that owns the service.
  446. *
  447. * @return The service interface implementing the specified service type.
  448. * Ownership of the service interface is not transferred to the caller.
  449. */
  450. template <typename Service>
  451. friend Service& use_service(io_service& ios);
  452. /// Add a service object to the io_service.
  453. /**
  454. * This function is used to add a service to the io_service.
  455. *
  456. * @param ios The io_service object that owns the service.
  457. *
  458. * @param svc The service object. On success, ownership of the service object
  459. * is transferred to the io_service. When the io_service object is destroyed,
  460. * it will destroy the service object by performing:
  461. * @code delete static_cast<io_service::service*>(svc) @endcode
  462. *
  463. * @throws asio::service_already_exists Thrown if a service of the
  464. * given type is already present in the io_service.
  465. *
  466. * @throws asio::invalid_service_owner Thrown if the service's owning
  467. * io_service is not the io_service object specified by the ios parameter.
  468. */
  469. template <typename Service>
  470. friend void add_service(io_service& ios, Service* svc);
  471. /// Determine if an io_service contains a specified service type.
  472. /**
  473. * This function is used to determine whether the io_service contains a
  474. * service object corresponding to the given service type.
  475. *
  476. * @param ios The io_service object that owns the service.
  477. *
  478. * @return A boolean indicating whether the io_service contains the service.
  479. */
  480. template <typename Service>
  481. friend bool has_service(io_service& ios);
  482. private:
  483. #if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  484. detail::winsock_init<> init_;
  485. #elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \
  486. || defined(__osf__)
  487. detail::signal_init<> init_;
  488. #endif
  489. // The service registry.
  490. asio::detail::service_registry* service_registry_;
  491. // The implementation.
  492. impl_type& impl_;
  493. };
  494. /// Class to inform the io_service when it has work to do.
  495. /**
  496. * The work class is used to inform the io_service when work starts and
  497. * finishes. This ensures that the io_service object's run() function will not
  498. * exit while work is underway, and that it does exit when there is no
  499. * unfinished work remaining.
  500. *
  501. * The work class is copy-constructible so that it may be used as a data member
  502. * in a handler class. It is not assignable.
  503. */
  504. class io_service::work
  505. {
  506. public:
  507. /// Constructor notifies the io_service that work is starting.
  508. /**
  509. * The constructor is used to inform the io_service that some work has begun.
  510. * This ensures that the io_service object's run() function will not exit
  511. * while the work is underway.
  512. */
  513. explicit work(asio::io_service& io_service);
  514. /// Copy constructor notifies the io_service that work is starting.
  515. /**
  516. * The constructor is used to inform the io_service that some work has begun.
  517. * This ensures that the io_service object's run() function will not exit
  518. * while the work is underway.
  519. */
  520. work(const work& other);
  521. /// Destructor notifies the io_service that the work is complete.
  522. /**
  523. * The destructor is used to inform the io_service that some work has
  524. * finished. Once the count of unfinished work reaches zero, the io_service
  525. * object's run() function is permitted to exit.
  526. */
  527. ~work();
  528. /// (Deprecated: use get_io_service().) Get the io_service associated with the
  529. /// work.
  530. asio::io_service& io_service();
  531. /// Get the io_service associated with the work.
  532. asio::io_service& get_io_service();
  533. private:
  534. // Prevent assignment.
  535. void operator=(const work& other);
  536. // The io_service.
  537. asio::io_service& io_service_;
  538. };
  539. /// Class used to uniquely identify a service.
  540. class io_service::id
  541. : private noncopyable
  542. {
  543. public:
  544. /// Constructor.
  545. id() {}
  546. };
  547. /// Base class for all io_service services.
  548. class io_service::service
  549. : private noncopyable
  550. {
  551. public:
  552. /// (Deprecated: use get_io_service().) Get the io_service object that owns
  553. /// the service.
  554. asio::io_service& io_service();
  555. /// Get the io_service object that owns the service.
  556. asio::io_service& get_io_service();
  557. protected:
  558. /// Constructor.
  559. /**
  560. * @param owner The io_service object that owns the service.
  561. */
  562. service(asio::io_service& owner);
  563. /// Destructor.
  564. virtual ~service();
  565. private:
  566. /// Destroy all user-defined handler objects owned by the service.
  567. virtual void shutdown_service() = 0;
  568. friend class asio::detail::service_registry;
  569. struct key
  570. {
  571. key() : type_info_(0), id_(0) {}
  572. const std::type_info* type_info_;
  573. const asio::io_service::id* id_;
  574. } key_;
  575. asio::io_service& owner_;
  576. service* next_;
  577. };
  578. /// Exception thrown when trying to add a duplicate service to an io_service.
  579. class service_already_exists
  580. : public std::logic_error
  581. {
  582. public:
  583. service_already_exists()
  584. : std::logic_error("Service already exists.")
  585. {
  586. }
  587. };
  588. /// Exception thrown when trying to add a service object to an io_service where
  589. /// the service has a different owner.
  590. class invalid_service_owner
  591. : public std::logic_error
  592. {
  593. public:
  594. invalid_service_owner()
  595. : std::logic_error("Invalid service owner.")
  596. {
  597. }
  598. };
  599. } // namespace asio
  600. #include "asio/impl/io_service.ipp"
  601. #include "asio/detail/pop_options.hpp"
  602. #endif // ASIO_IO_SERVICE_HPP