win_iocp_io_context.hpp 11 KB

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