win_iocp_io_context.hpp 12 KB

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