win_iocp_io_service.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. //
  2. // detail/win_iocp_io_service.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2015 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_DETAIL_WIN_IOCP_IO_SERVICE_HPP
  11. #define ASIO_DETAIL_WIN_IOCP_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/config.hpp"
  16. #if defined(ASIO_HAS_IOCP)
  17. #include "asio/io_service.hpp"
  18. #include "asio/detail/call_stack.hpp"
  19. #include "asio/detail/limits.hpp"
  20. #include "asio/detail/mutex.hpp"
  21. #include "asio/detail/op_queue.hpp"
  22. #include "asio/detail/scoped_ptr.hpp"
  23. #include "asio/detail/socket_types.hpp"
  24. #include "asio/detail/thread.hpp"
  25. #include "asio/detail/timer_queue_base.hpp"
  26. #include "asio/detail/timer_queue_set.hpp"
  27. #include "asio/detail/wait_op.hpp"
  28. #include "asio/detail/win_iocp_operation.hpp"
  29. #include "asio/detail/win_iocp_thread_info.hpp"
  30. #include "asio/detail/push_options.hpp"
  31. namespace asio {
  32. namespace detail {
  33. class wait_op;
  34. class win_iocp_io_service
  35. : public asio::detail::service_base<win_iocp_io_service>
  36. {
  37. public:
  38. // Constructor. Specifies a concurrency hint that is passed through to the
  39. // underlying I/O completion port.
  40. ASIO_DECL win_iocp_io_service(asio::io_service& io_service,
  41. size_t concurrency_hint = 0);
  42. // Destroy all user-defined handler objects owned by the service.
  43. ASIO_DECL void shutdown_service();
  44. // Initialise the task. Nothing to do here.
  45. void init_task()
  46. {
  47. }
  48. // Register a handle with the IO completion port.
  49. ASIO_DECL asio::error_code register_handle(
  50. HANDLE handle, asio::error_code& ec);
  51. // Run the event loop until stopped or no more work.
  52. ASIO_DECL size_t run(asio::error_code& ec);
  53. // Run until stopped or one operation is performed.
  54. ASIO_DECL size_t run_one(asio::error_code& ec);
  55. // Poll for operations without blocking.
  56. ASIO_DECL size_t poll(asio::error_code& ec);
  57. // Poll for one operation without blocking.
  58. ASIO_DECL size_t poll_one(asio::error_code& ec);
  59. // Stop the event processing loop.
  60. ASIO_DECL void stop();
  61. // Determine whether the io_service is stopped.
  62. bool stopped() const
  63. {
  64. return ::InterlockedExchangeAdd(&stopped_, 0) != 0;
  65. }
  66. // Reset in preparation for a subsequent run invocation.
  67. void reset()
  68. {
  69. ::InterlockedExchange(&stopped_, 0);
  70. }
  71. // Notify that some work has started.
  72. void work_started()
  73. {
  74. ::InterlockedIncrement(&outstanding_work_);
  75. }
  76. // Notify that some work has finished.
  77. void work_finished()
  78. {
  79. if (::InterlockedDecrement(&outstanding_work_) == 0)
  80. stop();
  81. }
  82. // Return whether a handler can be dispatched immediately.
  83. bool can_dispatch()
  84. {
  85. return thread_call_stack::contains(this) != 0;
  86. }
  87. // Request invocation of the given handler.
  88. template <typename Handler>
  89. void dispatch(Handler& handler);
  90. // Request invocation of the given handler and return immediately.
  91. template <typename Handler>
  92. void post(Handler& handler);
  93. // Request invocation of the given operation and return immediately. Assumes
  94. // that work_started() has not yet been called for the operation.
  95. void post_immediate_completion(win_iocp_operation* op, bool)
  96. {
  97. work_started();
  98. post_deferred_completion(op);
  99. }
  100. // Request invocation of the given operation and return immediately. Assumes
  101. // that work_started() was previously called for the operation.
  102. ASIO_DECL void post_deferred_completion(win_iocp_operation* op);
  103. // Request invocation of the given operation and return immediately. Assumes
  104. // that work_started() was previously called for the operations.
  105. ASIO_DECL void post_deferred_completions(
  106. op_queue<win_iocp_operation>& ops);
  107. // Request invocation of the given operation using the thread-private queue
  108. // and return immediately. Assumes that work_started() has not yet been
  109. // called for the operation.
  110. void post_private_immediate_completion(win_iocp_operation* op)
  111. {
  112. post_immediate_completion(op, false);
  113. }
  114. // Request invocation of the given operation using the thread-private queue
  115. // and return immediately. Assumes that work_started() was previously called
  116. // for the operation.
  117. void post_private_deferred_completion(win_iocp_operation* op)
  118. {
  119. post_deferred_completion(op);
  120. }
  121. // Process unfinished operations as part of a shutdown_service operation.
  122. // Assumes that work_started() was previously called for the operations.
  123. ASIO_DECL void abandon_operations(op_queue<operation>& ops);
  124. // Called after starting an overlapped I/O operation that did not complete
  125. // immediately. The caller must have already called work_started() prior to
  126. // starting the operation.
  127. ASIO_DECL void on_pending(win_iocp_operation* op);
  128. // Called after starting an overlapped I/O operation that completed
  129. // immediately. The caller must have already called work_started() prior to
  130. // starting the operation.
  131. ASIO_DECL void on_completion(win_iocp_operation* op,
  132. DWORD last_error = 0, DWORD bytes_transferred = 0);
  133. // Called after starting an overlapped I/O operation that completed
  134. // immediately. The caller must have already called work_started() prior to
  135. // starting the operation.
  136. ASIO_DECL void on_completion(win_iocp_operation* op,
  137. const asio::error_code& ec, DWORD bytes_transferred = 0);
  138. // Add a new timer queue to the service.
  139. template <typename Time_Traits>
  140. void add_timer_queue(timer_queue<Time_Traits>& timer_queue);
  141. // Remove a timer queue from the service.
  142. template <typename Time_Traits>
  143. void remove_timer_queue(timer_queue<Time_Traits>& timer_queue);
  144. // Schedule a new operation in the given timer queue to expire at the
  145. // specified absolute time.
  146. template <typename Time_Traits>
  147. void schedule_timer(timer_queue<Time_Traits>& queue,
  148. const typename Time_Traits::time_type& time,
  149. typename timer_queue<Time_Traits>::per_timer_data& timer, wait_op* op);
  150. // Cancel the timer associated with the given token. Returns the number of
  151. // handlers that have been posted or dispatched.
  152. template <typename Time_Traits>
  153. std::size_t cancel_timer(timer_queue<Time_Traits>& queue,
  154. typename timer_queue<Time_Traits>::per_timer_data& timer,
  155. std::size_t max_cancelled = (std::numeric_limits<std::size_t>::max)());
  156. private:
  157. #if defined(WINVER) && (WINVER < 0x0500)
  158. typedef DWORD dword_ptr_t;
  159. typedef ULONG ulong_ptr_t;
  160. #else // defined(WINVER) && (WINVER < 0x0500)
  161. typedef DWORD_PTR dword_ptr_t;
  162. typedef ULONG_PTR ulong_ptr_t;
  163. #endif // defined(WINVER) && (WINVER < 0x0500)
  164. // Dequeues at most one operation from the I/O completion port, and then
  165. // executes it. Returns the number of operations that were dequeued (i.e.
  166. // either 0 or 1).
  167. ASIO_DECL size_t do_one(bool block, asio::error_code& ec);
  168. // Helper to calculate the GetQueuedCompletionStatus timeout.
  169. ASIO_DECL static DWORD get_gqcs_timeout();
  170. // Helper function to add a new timer queue.
  171. ASIO_DECL void do_add_timer_queue(timer_queue_base& queue);
  172. // Helper function to remove a timer queue.
  173. ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue);
  174. // Called to recalculate and update the timeout.
  175. ASIO_DECL void update_timeout();
  176. // Helper class to call work_finished() on block exit.
  177. struct work_finished_on_block_exit;
  178. // Helper class for managing a HANDLE.
  179. struct auto_handle
  180. {
  181. HANDLE handle;
  182. auto_handle() : handle(0) {}
  183. ~auto_handle() { if (handle) ::CloseHandle(handle); }
  184. };
  185. // The IO completion port used for queueing operations.
  186. auto_handle iocp_;
  187. // The count of unfinished work.
  188. long outstanding_work_;
  189. // Flag to indicate whether the event loop has been stopped.
  190. mutable long stopped_;
  191. // Flag to indicate whether there is an in-flight stop event. Every event
  192. // posted using PostQueuedCompletionStatus consumes non-paged pool, so to
  193. // avoid exhausting this resouce we limit the number of outstanding events.
  194. long stop_event_posted_;
  195. // Flag to indicate whether the service has been shut down.
  196. long shutdown_;
  197. enum
  198. {
  199. // Timeout to use with GetQueuedCompletionStatus on older versions of
  200. // Windows. Some versions of windows have a "bug" where a call to
  201. // GetQueuedCompletionStatus can appear stuck even though there are events
  202. // waiting on the queue. Using a timeout helps to work around the issue.
  203. default_gqcs_timeout = 500,
  204. // Maximum waitable timer timeout, in milliseconds.
  205. max_timeout_msec = 5 * 60 * 1000,
  206. // Maximum waitable timer timeout, in microseconds.
  207. max_timeout_usec = max_timeout_msec * 1000,
  208. // Completion key value used to wake up a thread to dispatch timers or
  209. // completed operations.
  210. wake_for_dispatch = 1,
  211. // Completion key value to indicate that an operation has posted with the
  212. // original last_error and bytes_transferred values stored in the fields of
  213. // the OVERLAPPED structure.
  214. overlapped_contains_result = 2
  215. };
  216. // Timeout to use with GetQueuedCompletionStatus.
  217. const DWORD gqcs_timeout_;
  218. // Function object for processing timeouts in a background thread.
  219. struct timer_thread_function;
  220. friend struct timer_thread_function;
  221. // Background thread used for processing timeouts.
  222. scoped_ptr<thread> timer_thread_;
  223. // A waitable timer object used for waiting for timeouts.
  224. auto_handle waitable_timer_;
  225. // Non-zero if timers or completed operations need to be dispatched.
  226. long dispatch_required_;
  227. // Mutex for protecting access to the timer queues and completed operations.
  228. mutex dispatch_mutex_;
  229. // The timer queues.
  230. timer_queue_set timer_queues_;
  231. // The operations that are ready to dispatch.
  232. op_queue<win_iocp_operation> completed_ops_;
  233. // Per-thread call stack to track the state of each thread in the io_service.
  234. typedef call_stack<win_iocp_io_service,
  235. win_iocp_thread_info> thread_call_stack;
  236. };
  237. } // namespace detail
  238. } // namespace asio
  239. #include "asio/detail/pop_options.hpp"
  240. #include "asio/detail/impl/win_iocp_io_service.hpp"
  241. #if defined(ASIO_HEADER_ONLY)
  242. # include "asio/detail/impl/win_iocp_io_service.ipp"
  243. #endif // defined(ASIO_HEADER_ONLY)
  244. #endif // defined(ASIO_HAS_IOCP)
  245. #endif // ASIO_DETAIL_WIN_IOCP_IO_SERVICE_HPP