1 // <experimental/io_service> -*- C++ -*-
3 // Copyright (C) 2015-2024 Free Software Foundation, Inc.
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
25 /** @file experimental/io_context
26 * This is a TS C++ Library header.
27 * @ingroup networking-ts
30 #ifndef _GLIBCXX_EXPERIMENTAL_IO_SERVICE
31 #define _GLIBCXX_EXPERIMENTAL_IO_SERVICE 1
33 #pragma GCC system_header
35 #include <bits/requires_hosted.h> // experimental is currently omitted
37 #if __cplusplus >= 201402L
40 #include <forward_list>
42 #include <system_error>
45 #include <experimental/netfwd>
46 #include <experimental/executor>
47 #include <bits/chrono.h>
48 #if _GLIBCXX_HAVE_UNISTD_H
51 #ifdef _GLIBCXX_HAVE_POLL_H
54 #ifdef _GLIBCXX_HAVE_FCNTL_H
58 namespace std _GLIBCXX_VISIBILITY(default)
60 _GLIBCXX_BEGIN_NAMESPACE_VERSION
61 namespace experimental
68 /** @addtogroup networking-ts
74 /// An ExecutionContext for I/O operations.
75 class io_context : public execution_context
80 /// An executor for an io_context.
84 // construct / copy / destroy:
86 executor_type(const executor_type& __other) noexcept = default;
87 executor_type(executor_type&& __other) noexcept = default;
89 executor_type& operator=(const executor_type& __other) noexcept = default;
90 executor_type& operator=(executor_type&& __other) noexcept = default;
92 // executor operations:
94 bool running_in_this_thread() const noexcept
96 #ifdef _GLIBCXX_HAS_GTHREADS
97 lock_guard<execution_context::mutex_type> __lock(_M_ctx->_M_mtx);
98 auto __end = _M_ctx->_M_call_stack.end();
99 return std::find(_M_ctx->_M_call_stack.begin(), __end,
100 this_thread::get_id()) != __end;
102 return _M_ctx->_M_run_count != 0;
106 io_context& context() const noexcept { return *_M_ctx; }
108 void on_work_started() const noexcept { ++_M_ctx->_M_work_count; }
109 void on_work_finished() const noexcept { --_M_ctx->_M_work_count; }
111 template<typename _Func, typename _ProtoAllocator>
113 dispatch(_Func&& __f, const _ProtoAllocator& __a) const
115 if (running_in_this_thread())
116 decay_t<_Func>{std::forward<_Func>(__f)}();
118 post(std::forward<_Func>(__f), __a);
121 template<typename _Func, typename _ProtoAllocator>
123 post(_Func&& __f, const _ProtoAllocator& __a) const
125 lock_guard<execution_context::mutex_type> __lock(_M_ctx->_M_mtx);
126 // TODO (re-use functionality in system_context)
127 _M_ctx->_M_reactor._M_notify();
130 template<typename _Func, typename _ProtoAllocator>
132 defer(_Func&& __f, const _ProtoAllocator& __a) const
133 { post(std::forward<_Func>(__f), __a); }
139 executor_type(io_context& __ctx) : _M_ctx(std::addressof(__ctx)) { }
144 using count_type = size_t;
146 // construct / copy / destroy:
148 io_context() : _M_work_count(0) { }
151 io_context(int __concurrency_hint) : _M_work_count(0) { }
153 io_context(const io_context&) = delete;
154 io_context& operator=(const io_context&) = delete;
156 // io_context operations:
158 executor_type get_executor() noexcept { return executor_type(*this); }
165 if (__n != numeric_limits<count_type>::max())
170 template<typename _Rep, typename _Period>
172 run_for(const chrono::duration<_Rep, _Period>& __rel_time)
173 { return run_until(chrono::steady_clock::now() + __rel_time); }
175 template<typename _Clock, typename _Duration>
177 run_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
180 while (run_one_until(__abs_time))
181 if (__n != numeric_limits<count_type>::max())
188 { return _M_do_one(chrono::milliseconds{-1}); }
190 template<typename _Rep, typename _Period>
192 run_one_for(const chrono::duration<_Rep, _Period>& __rel_time)
193 { return run_one_until(chrono::steady_clock::now() + __rel_time); }
195 template<typename _Clock, typename _Duration>
197 run_one_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
199 auto __now = _Clock::now();
200 while (__now < __abs_time)
202 using namespace std::chrono;
203 auto __ms = duration_cast<milliseconds>(__abs_time - __now);
206 __now = _Clock::now();
216 if (__n != numeric_limits<count_type>::max())
223 { return _M_do_one(chrono::milliseconds{0}); }
227 lock_guard<execution_context::mutex_type> __lock(_M_mtx);
229 _M_reactor._M_notify();
232 bool stopped() const noexcept
234 lock_guard<execution_context::mutex_type> __lock(_M_mtx);
245 template<typename _Clock, typename _WaitTraits>
246 friend class basic_waitable_timer;
248 friend __socket_impl;
250 template<typename _Protocol>
251 friend class __basic_socket_impl;
253 template<typename _Protocol>
254 friend class basic_socket;
256 template<typename _Protocol>
257 friend class basic_datagram_socket;
259 template<typename _Protocol>
260 friend class basic_stream_socket;
262 template<typename _Protocol>
263 friend class basic_socket_acceptor;
266 _M_outstanding_work() const
267 { return _M_work_count + !_M_ops.empty(); }
269 struct __timer_queue_base : execution_context::service
271 // return milliseconds until next timer expires, or milliseconds::max()
272 virtual chrono::milliseconds _M_next() const = 0;
273 virtual bool run_one() = 0;
277 __timer_queue_base(execution_context& __ctx) : service(__ctx)
279 auto& __ioc = static_cast<io_context&>(__ctx);
280 lock_guard<execution_context::mutex_type> __lock(__ioc._M_mtx);
281 __ioc._M_timers.push_back(this);
284 mutable execution_context::mutex_type _M_qmtx;
287 template<typename _Timer, typename _Key = typename _Timer::_Key>
288 struct __timer_queue : __timer_queue_base
290 using key_type = __timer_queue;
293 __timer_queue(execution_context& __ctx) : __timer_queue_base(__ctx)
296 void shutdown() noexcept { }
298 io_context& context() noexcept
299 { return static_cast<io_context&>(service::context()); }
301 // Start an asynchronous wait.
303 push(const _Timer& __t, function<void(error_code)> __h)
305 context().get_executor().on_work_started();
306 lock_guard<execution_context::mutex_type> __lock(_M_qmtx);
307 _M_queue.emplace(__t, _M_next_id++, std::move(__h));
308 // no need to notify reactor unless this timer went to the front?
311 // Cancel all outstanding waits for __t
313 cancel(const _Timer& __t)
315 lock_guard<execution_context::mutex_type> __lock(_M_qmtx);
317 auto __last = _M_queue.end();
318 for (auto __it = _M_queue.begin(), __end = __last; __it != __end;
321 if (__it->_M_key == __t._M_key.get())
329 _M_queue._M_sort_to(__last);
333 // Cancel oldest outstanding wait for __t
335 cancel_one(const _Timer& __t)
337 lock_guard<execution_context::mutex_type> __lock(_M_qmtx);
338 const auto __end = _M_queue.end();
339 auto __oldest = __end;
340 for (auto __it = _M_queue.begin(); __it != __end; ++__it)
341 if (__it->_M_key == __t._M_key.get())
342 if (__oldest == __end || __it->_M_id < __oldest->_M_id)
344 if (__oldest == __end)
347 _M_queue._M_sort_to(__oldest);
352 _M_next() const override
354 typename _Timer::time_point __exp;
356 lock_guard<execution_context::mutex_type> __lock(_M_qmtx);
357 if (_M_queue.empty())
358 return chrono::milliseconds::max(); // no pending timers
359 if (_M_queue.top()._M_key == nullptr)
360 return chrono::milliseconds::zero(); // cancelled, run now
361 __exp = _M_queue.top()._M_expiry;
363 auto __dur = _Timer::traits_type::to_wait_duration(__exp);
364 if (__dur < __dur.zero())
365 __dur = __dur.zero();
366 return chrono::duration_cast<chrono::milliseconds>(__dur);
371 bool run_one() override
373 auto __now = _Timer::clock_type::now();
374 function<void(error_code)> __h;
377 lock_guard<execution_context::mutex_type> __lock(_M_qmtx);
379 if (_M_queue.top()._M_key == nullptr) // cancelled
381 __h = std::move(_M_queue.top()._M_h);
382 __ec = std::make_error_code(errc::operation_canceled);
385 else if (_M_queue.top()._M_expiry <= _Timer::clock_type::now())
387 __h = std::move(_M_queue.top()._M_h);
394 context().get_executor().on_work_finished();
400 using __timer_id_type = uint64_t;
402 struct __pending_timer
404 __pending_timer(const _Timer& __t, uint64_t __id,
405 function<void(error_code)> __h)
406 : _M_expiry(__t.expiry()), _M_key(__t._M_key.get()), _M_id(__id),
410 typename _Timer::time_point _M_expiry;
412 __timer_id_type _M_id;
413 function<void(error_code)> _M_h;
415 void cancel() { _M_expiry = _M_expiry.min(); _M_key = nullptr; }
418 operator<(const __pending_timer& __rhs) const
419 { return _M_expiry < __rhs._M_expiry; }
422 struct __queue : priority_queue<__pending_timer>
425 typename priority_queue<__pending_timer>::container_type::iterator;
427 // expose begin/end/erase for direct access to underlying container
428 iterator begin() { return this->c.begin(); }
429 iterator end() { return this->c.end(); }
430 iterator erase(iterator __it) { return this->c.erase(__it); }
433 _M_sort_to(iterator __it)
434 { std::stable_sort(this->c.begin(), ++__it); }
438 __timer_id_type _M_next_id = 0;
441 template<typename _Timer, typename _CompletionHandler>
443 async_wait(const _Timer& __timer, _CompletionHandler&& __h)
445 auto& __queue = use_service<__timer_queue<_Timer>>(*this);
446 __queue.push(__timer, std::move(__h));
447 _M_reactor._M_notify();
450 // Cancel all wait operations initiated by __timer.
451 template<typename _Timer>
453 cancel(const _Timer& __timer)
455 if (!has_service<__timer_queue<_Timer>>(*this))
458 auto __c = use_service<__timer_queue<_Timer>>(*this).cancel(__timer);
460 _M_reactor._M_notify();
464 // Cancel the oldest wait operation initiated by __timer.
465 template<typename _Timer>
467 cancel_one(const _Timer& __timer)
469 if (!has_service<__timer_queue<_Timer>>(*this))
472 if (use_service<__timer_queue<_Timer>>(*this).cancel_one(__timer))
474 _M_reactor._M_notify();
480 // The caller must know what the wait-type __w will be interpreted.
481 // In the current implementation the reactor is based on <poll.h>
482 // so the parameter must be one of POLLIN, POLLOUT or POLLERR.
483 template<typename _Op>
485 async_wait(int __fd, int __w, _Op&& __op)
487 lock_guard<execution_context::mutex_type> __lock(_M_mtx);
488 // TODO need push_back, use std::list not std::forward_list
489 auto __tail = _M_ops.before_begin(), __it = _M_ops.begin();
490 while (__it != _M_ops.end())
495 using __type = __async_operation_impl<_Op>;
496 _M_ops.emplace_after(__tail,
497 make_unique<__type>(std::move(__op), __fd, __w));
498 _M_reactor._M_fd_interest(__fd, __w);
501 void _M_add_fd(int __fd) { _M_reactor._M_add_fd(__fd); }
502 void _M_remove_fd(int __fd) { _M_reactor._M_remove_fd(__fd); }
504 void cancel(int __fd, error_code&)
506 lock_guard<execution_context::mutex_type> __lock(_M_mtx);
507 const auto __end = _M_ops.end();
508 auto __it = _M_ops.begin();
509 auto __prev = _M_ops.before_begin();
510 while (__it != __end && (*__it)->_M_is_cancelled())
515 auto __cancelled = __prev;
516 while (__it != __end)
518 if ((*__it)->_M_fd == __fd)
522 _M_ops.splice_after(__cancelled, _M_ops, __prev);
531 _M_reactor._M_not_interested(__fd);
534 struct __async_operation
536 __async_operation(int __fd, int __ev) : _M_fd(__fd), _M_ev(__ev) { }
538 virtual ~__async_operation() = default;
543 void cancel() { _M_fd = -1; }
544 bool _M_is_cancelled() const { return _M_fd == -1; }
545 virtual void run(io_context&) = 0;
548 template<typename _Op>
549 struct __async_operation_impl : __async_operation
551 __async_operation_impl(_Op&& __op, int __fd, int __ev)
552 : __async_operation{__fd, __ev}, _M_op(std::move(__op)) { }
556 void run(io_context& __ctx)
558 if (_M_is_cancelled())
559 _M_op(std::make_error_code(errc::operation_canceled));
565 #ifdef _GLIBCXX_HAS_GTHREADS
566 atomic<count_type> _M_work_count;
568 count_type _M_work_count;
570 mutable execution_context::mutex_type _M_mtx;
571 queue<function<void()>> _M_op;
572 bool _M_stopped = false;
576 __monitor(io_context& __c) : _M_ctx(__c)
578 #ifdef _GLIBCXX_HAS_GTHREADS
579 lock_guard<execution_context::mutex_type> __lock(_M_ctx._M_mtx);
580 _M_ctx._M_call_stack.push_back(this_thread::get_id());
582 _M_ctx._M_run_count++;
588 #ifdef _GLIBCXX_HAS_GTHREADS
589 lock_guard<execution_context::mutex_type> __lock(_M_ctx._M_mtx);
590 _M_ctx._M_call_stack.pop_back();
592 _M_ctx._M_run_count--;
594 if (_M_ctx._M_outstanding_work() == 0)
596 _M_ctx._M_stopped = true;
597 _M_ctx._M_reactor._M_notify();
601 __monitor(__monitor&&) = delete;
607 _M_do_one(chrono::milliseconds __timeout)
609 const bool __block = __timeout != chrono::milliseconds::zero();
611 __reactor::__fdvec __fds;
613 __monitor __mon{*this};
615 __timer_queue_base* __timerq = nullptr;
616 unique_ptr<__async_operation> __async_op;
622 if (__timerq->run_one())
630 __async_op->run(*this);
631 // TODO need to unregister __async_op
635 chrono::milliseconds __ms{0};
638 lock_guard<execution_context::mutex_type> __lock(_M_mtx);
643 // find first timer with something to do
644 for (auto __q : _M_timers)
646 auto __next = __q->_M_next();
647 if (__next == __next.zero()) // ready to run immediately
653 else if (__next != __next.max() && __block
654 && (__next < __ms || __timerq == nullptr))
661 if (__timerq && __ms == __ms.zero())
662 continue; // restart loop to run a timer immediately
664 if (!_M_ops.empty() && _M_ops.front()->_M_is_cancelled())
666 _M_ops.front().swap(__async_op);
671 // TODO run any posted items
675 if (__timerq == nullptr)
677 else if (__ms.zero() <= __timeout && __timeout < __ms)
679 else if (__ms.count() > numeric_limits<int>::max())
680 __ms = chrono::milliseconds{numeric_limits<int>::max()};
682 // else __ms == 0 and poll() will return immediately
686 auto __res = _M_reactor.wait(__fds, __ms);
688 if (__res == __reactor::_S_retry)
691 if (__res == __reactor::_S_timeout)
693 if (__timerq == nullptr)
696 continue; // timed out, so restart loop and process the timer
701 if (__fds.empty()) // nothing to do
704 lock_guard<execution_context::mutex_type> __lock(_M_mtx);
705 for (auto __it = _M_ops.begin(), __end = _M_ops.end(),
706 __prev = _M_ops.before_begin(); __it != __end; ++__it, ++__prev)
709 auto __pos = std::lower_bound(__fds.begin(), __fds.end(),
711 [](const auto& __p, int __fd) { return __p.fd < __fd; });
712 if (__pos != __fds.end() && __pos->fd == __op._M_fd
713 && __pos->revents & __op._M_ev)
715 __it->swap(__async_op);
716 _M_ops.erase_after(__prev);
717 break; // restart loop and run op
725 #ifdef _GLIBCXX_HAVE_POLL_H
726 __reactor() : _M_fds(1)
729 if (::pipe(__pipe) == -1)
730 __throw_system_error(errno);
731 if (::fcntl(__pipe[0], F_SETFL, O_NONBLOCK) == -1
732 || ::fcntl(__pipe[1], F_SETFL, O_NONBLOCK) == -1)
737 __throw_system_error(__e);
739 _M_fds.back().events = POLLIN;
740 _M_fds.back().fd = __pipe[0];
741 _M_notify_wr = __pipe[1];
746 ::close(_M_fds.back().fd);
747 ::close(_M_notify_wr);
751 // write a notification byte to the pipe (ignoring errors)
756 __n = ::write(_M_notify_wr, "", 1);
757 } while (__n == -1 && errno == EINTR);
760 // read all notification bytes from the pipe
767 __n = ::read(_M_fds.back().fd, __buf, sizeof(__buf));
768 } while (__n != -1 || errno == EINTR);
774 auto __pos = _M_lower_bound(__fd);
775 if (__pos->fd == __fd)
776 __throw_system_error((int)errc::invalid_argument);
777 _M_fds.insert(__pos, __fdvec::value_type{})->fd = __fd;
782 _M_remove_fd(int __fd)
784 auto __pos = _M_lower_bound(__fd);
785 if (__pos->fd == __fd)
792 _M_fd_interest(int __fd, int __w)
794 auto __pos = _M_lower_bound(__fd);
795 if (__pos->fd == __fd)
796 __pos->events |= __w;
802 _M_not_interested(int __fd)
804 auto __pos = _M_lower_bound(__fd);
805 if (__pos->fd == __fd)
810 #ifdef _GLIBCXX_HAVE_POLL_H
811 using __fdvec = vector<::pollfd>;
813 struct dummy_pollfd { int fd = -1; short events = 0, revents = 0; };
814 using __fdvec = vector<dummy_pollfd>;
817 // Find first element p such that !(p.fd < __fd)
818 // N.B. always returns a dereferencable iterator.
820 _M_lower_bound(int __fd)
822 return std::lower_bound(_M_fds.begin(), _M_fds.end() - 1,
823 __fd, [](const auto& __p, int __fd) { return __p.fd < __fd; });
826 enum __status { _S_retry, _S_timeout, _S_ok, _S_error };
829 wait(__fdvec& __fds, chrono::milliseconds __timeout)
831 #ifdef _GLIBCXX_HAVE_POLL_H
832 // XXX not thread-safe!
833 __fds = _M_fds; // take snapshot to pass to poll()
835 int __res = ::poll(__fds.data(), __fds.size(), __timeout.count());
842 return _S_error; // XXX ???
849 else if (__fds.back().revents != 0) // something changed, restart
856 auto __part = std::stable_partition(__fds.begin(), __fds.end() - 1,
857 [](const __fdvec::value_type& __p) { return __p.revents != 0; });
858 __fds.erase(__part, __fds.end());
868 __fdvec _M_fds; // _M_fds.back() is the read end of the self-pipe
869 int _M_notify_wr; // write end of the self-pipe
872 __reactor _M_reactor;
874 vector<__timer_queue_base*> _M_timers;
875 forward_list<unique_ptr<__async_operation>> _M_ops;
877 #ifdef _GLIBCXX_HAS_GTHREADS
878 vector<thread::id> _M_call_stack;
880 int _M_run_count = 0;
885 operator==(const io_context::executor_type& __a,
886 const io_context::executor_type& __b) noexcept
888 // https://github.com/chriskohlhoff/asio-tr2/issues/201
889 using executor_type = io_context::executor_type;
890 return std::addressof(executor_type(__a).context())
891 == std::addressof(executor_type(__b).context());
895 operator!=(const io_context::executor_type& __a,
896 const io_context::executor_type& __b) noexcept
897 { return !(__a == __b); }
899 template<> struct is_executor<io_context::executor_type> : true_type {};
905 } // namespace experimental
906 _GLIBCXX_END_NAMESPACE_VERSION
911 #endif // _GLIBCXX_EXPERIMENTAL_IO_SERVICE