2 // detail/win_iocp_io_context.hpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
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)
11 #ifndef BOOST_ASIO_DETAIL_WIN_IOCP_IO_CONTEXT_HPP
12 #define BOOST_ASIO_DETAIL_WIN_IOCP_IO_CONTEXT_HPP
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
18 #include <boost/asio/detail/config.hpp>
20 #if defined(BOOST_ASIO_HAS_IOCP)
22 #include <boost/asio/detail/limits.hpp>
23 #include <boost/asio/detail/mutex.hpp>
24 #include <boost/asio/detail/op_queue.hpp>
25 #include <boost/asio/detail/scoped_ptr.hpp>
26 #include <boost/asio/detail/socket_types.hpp>
27 #include <boost/asio/detail/thread.hpp>
28 #include <boost/asio/detail/thread_context.hpp>
29 #include <boost/asio/detail/timer_queue_base.hpp>
30 #include <boost/asio/detail/timer_queue_set.hpp>
31 #include <boost/asio/detail/wait_op.hpp>
32 #include <boost/asio/detail/win_iocp_operation.hpp>
33 #include <boost/asio/detail/win_iocp_thread_info.hpp>
34 #include <boost/asio/execution_context.hpp>
36 #include <boost/asio/detail/push_options.hpp>
44 class win_iocp_io_context
45 : public execution_context_service_base<win_iocp_io_context>,
49 // Constructor. Specifies a concurrency hint that is passed through to the
50 // underlying I/O completion port.
51 BOOST_ASIO_DECL win_iocp_io_context(boost::asio::execution_context& ctx,
52 int concurrency_hint = -1);
54 // Destroy all user-defined handler objects owned by the service.
55 BOOST_ASIO_DECL void shutdown();
57 // Initialise the task. Nothing to do here.
62 // Register a handle with the IO completion port.
63 BOOST_ASIO_DECL boost::system::error_code register_handle(
64 HANDLE handle, boost::system::error_code& ec);
66 // Run the event loop until stopped or no more work.
67 BOOST_ASIO_DECL size_t run(boost::system::error_code& ec);
69 // Run until stopped or one operation is performed.
70 BOOST_ASIO_DECL size_t run_one(boost::system::error_code& ec);
72 // Run until timeout, interrupted, or one operation is performed.
73 BOOST_ASIO_DECL size_t wait_one(long usec, boost::system::error_code& ec);
75 // Poll for operations without blocking.
76 BOOST_ASIO_DECL size_t poll(boost::system::error_code& ec);
78 // Poll for one operation without blocking.
79 BOOST_ASIO_DECL size_t poll_one(boost::system::error_code& ec);
81 // Stop the event processing loop.
82 BOOST_ASIO_DECL void stop();
84 // Determine whether the io_context is stopped.
87 return ::InterlockedExchangeAdd(&stopped_, 0) != 0;
90 // Restart in preparation for a subsequent run invocation.
93 ::InterlockedExchange(&stopped_, 0);
96 // Notify that some work has started.
99 ::InterlockedIncrement(&outstanding_work_);
102 // Notify that some work has finished.
105 if (::InterlockedDecrement(&outstanding_work_) == 0)
109 // Return whether a handler can be dispatched immediately.
112 return thread_call_stack::contains(this) != 0;
115 // Request invocation of the given operation and return immediately. Assumes
116 // that work_started() has not yet been called for the operation.
117 void post_immediate_completion(win_iocp_operation* op, bool)
120 post_deferred_completion(op);
123 // Request invocation of the given operation and return immediately. Assumes
124 // that work_started() was previously called for the operation.
125 BOOST_ASIO_DECL void post_deferred_completion(win_iocp_operation* op);
127 // Request invocation of the given operation and return immediately. Assumes
128 // that work_started() was previously called for the operations.
129 BOOST_ASIO_DECL void post_deferred_completions(
130 op_queue<win_iocp_operation>& ops);
132 // Request invocation of the given operation using the thread-private queue
133 // and return immediately. Assumes that work_started() has not yet been
134 // called for the operation.
135 void post_private_immediate_completion(win_iocp_operation* op)
137 post_immediate_completion(op, false);
140 // Request invocation of the given operation using the thread-private queue
141 // and return immediately. Assumes that work_started() was previously called
142 // for the operation.
143 void post_private_deferred_completion(win_iocp_operation* op)
145 post_deferred_completion(op);
148 // Enqueue the given operation following a failed attempt to dispatch the
149 // operation for immediate invocation.
150 void do_dispatch(operation* op)
152 post_immediate_completion(op, false);
155 // Process unfinished operations as part of a shutdown operation. Assumes
156 // that work_started() was previously called for the operations.
157 BOOST_ASIO_DECL void abandon_operations(op_queue<operation>& ops);
159 // Called after starting an overlapped I/O operation that did not complete
160 // immediately. The caller must have already called work_started() prior to
161 // starting the operation.
162 BOOST_ASIO_DECL void on_pending(win_iocp_operation* op);
164 // Called after starting an overlapped I/O operation that completed
165 // immediately. The caller must have already called work_started() prior to
166 // starting the operation.
167 BOOST_ASIO_DECL void on_completion(win_iocp_operation* op,
168 DWORD last_error = 0, DWORD bytes_transferred = 0);
170 // Called after starting an overlapped I/O operation that completed
171 // immediately. The caller must have already called work_started() prior to
172 // starting the operation.
173 BOOST_ASIO_DECL void on_completion(win_iocp_operation* op,
174 const boost::system::error_code& ec, DWORD bytes_transferred = 0);
176 // Add a new timer queue to the service.
177 template <typename Time_Traits>
178 void add_timer_queue(timer_queue<Time_Traits>& timer_queue);
180 // Remove a timer queue from the service.
181 template <typename Time_Traits>
182 void remove_timer_queue(timer_queue<Time_Traits>& timer_queue);
184 // Schedule a new operation in the given timer queue to expire at the
185 // specified absolute time.
186 template <typename Time_Traits>
187 void schedule_timer(timer_queue<Time_Traits>& queue,
188 const typename Time_Traits::time_type& time,
189 typename timer_queue<Time_Traits>::per_timer_data& timer, wait_op* op);
191 // Cancel the timer associated with the given token. Returns the number of
192 // handlers that have been posted or dispatched.
193 template <typename Time_Traits>
194 std::size_t cancel_timer(timer_queue<Time_Traits>& queue,
195 typename timer_queue<Time_Traits>::per_timer_data& timer,
196 std::size_t max_cancelled = (std::numeric_limits<std::size_t>::max)());
198 // Move the timer operations associated with the given timer.
199 template <typename Time_Traits>
200 void move_timer(timer_queue<Time_Traits>& queue,
201 typename timer_queue<Time_Traits>::per_timer_data& to,
202 typename timer_queue<Time_Traits>::per_timer_data& from);
204 // Get the concurrency hint that was used to initialise the io_context.
205 int concurrency_hint() const
207 return concurrency_hint_;
211 #if defined(WINVER) && (WINVER < 0x0500)
212 typedef DWORD dword_ptr_t;
213 typedef ULONG ulong_ptr_t;
214 #else // defined(WINVER) && (WINVER < 0x0500)
215 typedef DWORD_PTR dword_ptr_t;
216 typedef ULONG_PTR ulong_ptr_t;
217 #endif // defined(WINVER) && (WINVER < 0x0500)
219 // Dequeues at most one operation from the I/O completion port, and then
220 // executes it. Returns the number of operations that were dequeued (i.e.
222 BOOST_ASIO_DECL size_t do_one(DWORD msec, boost::system::error_code& ec);
224 // Helper to calculate the GetQueuedCompletionStatus timeout.
225 BOOST_ASIO_DECL static DWORD get_gqcs_timeout();
227 // Helper function to add a new timer queue.
228 BOOST_ASIO_DECL void do_add_timer_queue(timer_queue_base& queue);
230 // Helper function to remove a timer queue.
231 BOOST_ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue);
233 // Called to recalculate and update the timeout.
234 BOOST_ASIO_DECL void update_timeout();
236 // Helper class to call work_finished() on block exit.
237 struct work_finished_on_block_exit;
239 // Helper class for managing a HANDLE.
243 auto_handle() : handle(0) {}
244 ~auto_handle() { if (handle) ::CloseHandle(handle); }
247 // The IO completion port used for queueing operations.
250 // The count of unfinished work.
251 long outstanding_work_;
253 // Flag to indicate whether the event loop has been stopped.
254 mutable long stopped_;
256 // Flag to indicate whether there is an in-flight stop event. Every event
257 // posted using PostQueuedCompletionStatus consumes non-paged pool, so to
258 // avoid exhausting this resouce we limit the number of outstanding events.
259 long stop_event_posted_;
261 // Flag to indicate whether the service has been shut down.
266 // Timeout to use with GetQueuedCompletionStatus on older versions of
267 // Windows. Some versions of windows have a "bug" where a call to
268 // GetQueuedCompletionStatus can appear stuck even though there are events
269 // waiting on the queue. Using a timeout helps to work around the issue.
270 default_gqcs_timeout = 500,
272 // Maximum waitable timer timeout, in milliseconds.
273 max_timeout_msec = 5 * 60 * 1000,
275 // Maximum waitable timer timeout, in microseconds.
276 max_timeout_usec = max_timeout_msec * 1000,
278 // Completion key value used to wake up a thread to dispatch timers or
279 // completed operations.
280 wake_for_dispatch = 1,
282 // Completion key value to indicate that an operation has posted with the
283 // original last_error and bytes_transferred values stored in the fields of
284 // the OVERLAPPED structure.
285 overlapped_contains_result = 2
288 // Timeout to use with GetQueuedCompletionStatus.
289 const DWORD gqcs_timeout_;
291 // Function object for processing timeouts in a background thread.
292 struct timer_thread_function;
293 friend struct timer_thread_function;
295 // Background thread used for processing timeouts.
296 scoped_ptr<thread> timer_thread_;
298 // A waitable timer object used for waiting for timeouts.
299 auto_handle waitable_timer_;
301 // Non-zero if timers or completed operations need to be dispatched.
302 long dispatch_required_;
304 // Mutex for protecting access to the timer queues and completed operations.
305 mutex dispatch_mutex_;
308 timer_queue_set timer_queues_;
310 // The operations that are ready to dispatch.
311 op_queue<win_iocp_operation> completed_ops_;
313 // The concurrency hint used to initialise the io_context.
314 const int concurrency_hint_;
317 } // namespace detail
321 #include <boost/asio/detail/pop_options.hpp>
323 #include <boost/asio/detail/impl/win_iocp_io_context.hpp>
324 #if defined(BOOST_ASIO_HEADER_ONLY)
325 # include <boost/asio/detail/impl/win_iocp_io_context.ipp>
326 #endif // defined(BOOST_ASIO_HEADER_ONLY)
328 #endif // defined(BOOST_ASIO_HAS_IOCP)
330 #endif // BOOST_ASIO_DETAIL_WIN_IOCP_IO_CONTEXT_HPP