Skip to content

Commit db6bd60

Browse files
committed
perf: run handlers queued behind the reactor first while that pays off
When the reactor sentinel reached the front with handlers still queued, the scheduler polled the reactor without blocking before running them. Those handlers usually start the next I/O themselves, such as a coroutine an I/O completion woke, so running them first can save a reactor pass. The sentinel now moves behind the queued handlers once and polls on its next turn regardless, so handlers that keep reposting still cannot starve I/O. Waiting does not always pay: when the handlers drain the queue, the deferred turn has nothing left to overlap with, and where loopback data arrives later their I/O parks instead of completing. reactor_defer_policy scores each deferral by whether its turn still found handlers queued, and stops deferring while deferrals that empty the queue are frequent. Turns that poll instead let it try again. restart() forgets a pending deferral and the score, so a run stopped with the sentinel moved back doesn't cost the next run its own. poll() and poll_one() are unchanged.
1 parent efa2665 commit db6bd60

5 files changed

Lines changed: 429 additions & 11 deletions

File tree

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
//
2+
// Copyright (c) 2026 Steve Gerbino
3+
//
4+
// Distributed under the Boost Software License, Version 1.0. (See accompanying
5+
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6+
//
7+
// Official repository: https://github.com/cppalliance/corosio
8+
//
9+
10+
#ifndef BOOST_COROSIO_NATIVE_DETAIL_REACTOR_REACTOR_DEFER_POLICY_HPP
11+
#define BOOST_COROSIO_NATIVE_DETAIL_REACTOR_REACTOR_DEFER_POLICY_HPP
12+
13+
namespace boost::corosio::detail {
14+
15+
/** Decide whether the reactor sentinel waits behind queued handlers.
16+
17+
When the sentinel reaches the front of the queue with handlers still
18+
queued, running those handlers first usually saves a reactor pass:
19+
they tend to start the next I/O themselves. That bet loses when the
20+
handlers drain the queue, so the deferred turn has no other work to
21+
overlap with and a poll that would have found completed I/O comes too
22+
late. The policy scores each deferral by what the deferred turn found
23+
and stops deferring while losses are frequent.
24+
25+
A deferred turn that found the queue empty costs more than one that
26+
found handlers repays, so deferring continues only while fewer than
27+
about one deferral in `miss_cost + 1` empties the queue. Each turn
28+
that polls instead of deferring lets the score decay, so a workload
29+
that changes is tried again.
30+
31+
@par Thread Safety
32+
Distinct objects: Safe.
33+
Shared objects: Unsafe. The scheduler calls it under its own mutex.
34+
*/
35+
class reactor_defer_policy
36+
{
37+
int score_ = 0;
38+
39+
public:
40+
/// Score added by a deferred turn that found the queue empty.
41+
static constexpr int miss_cost = 8;
42+
43+
/// Score at or above which the sentinel polls instead of deferring.
44+
static constexpr int threshold = 8;
45+
46+
/// Highest score, which bounds how long deferring stays off.
47+
static constexpr int max_score = 64;
48+
49+
/// Check whether the sentinel may wait behind queued handlers.
50+
bool may_defer() const noexcept
51+
{
52+
return score_ < threshold;
53+
}
54+
55+
/** Record what a deferred turn of the sentinel found.
56+
57+
@param handlers_queued `true` if handlers were still queued, so
58+
the deferral cost nothing.
59+
*/
60+
void on_deferred_turn(bool handlers_queued) noexcept
61+
{
62+
if (handlers_queued)
63+
{
64+
if (score_ > 0)
65+
--score_;
66+
}
67+
else
68+
{
69+
score_ =
70+
score_ > max_score - miss_cost ? max_score : score_ + miss_cost;
71+
}
72+
}
73+
74+
/// Record a turn that polled because deferring was off.
75+
void on_polled_instead() noexcept
76+
{
77+
if (score_ > 0)
78+
--score_;
79+
}
80+
81+
/// Forget the history, as for a fresh run.
82+
void reset() noexcept
83+
{
84+
score_ = 0;
85+
}
86+
};
87+
88+
} // namespace boost::corosio::detail
89+
90+
#endif // BOOST_COROSIO_NATIVE_DETAIL_REACTOR_REACTOR_DEFER_POLICY_HPP

‎include/boost/corosio/native/detail/reactor/reactor_scheduler.hpp‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include <boost/corosio/detail/scheduler_op.hpp>
2121
#include <boost/corosio/detail/thread_local_ptr.hpp>
2222
#include <boost/corosio/detail/timer_service.hpp>
23+
#include <boost/corosio/native/detail/reactor/reactor_defer_policy.hpp>
2324

2425
#include <atomic>
2526
#include <chrono>
@@ -333,6 +334,11 @@ class reactor_scheduler : public scheduler
333334
std::atomic<bool> stopped_{false};
334335
mutable std::atomic<bool> task_running_{false};
335336
mutable bool task_interrupted_ = false;
337+
// Set while the sentinel waits behind queued handlers (guarded by
338+
// mutex_).
339+
bool task_deferred_ = false;
340+
// Whether waiting is paying off (guarded by mutex_).
341+
reactor_defer_policy defer_policy_;
336342

337343
// Descriptors retired during the running reactor pass (guarded by
338344
// mutex_).
@@ -1032,7 +1038,13 @@ reactor_scheduler::do_one(lock_type& lock, long timeout_us, context_type& ctx)
10321038
for (;;)
10331039
{
10341040
if (stopped_.load(std::memory_order_acquire))
1041+
{
1042+
// The next run is scored afresh, but a deferral left pending
1043+
// stays marked: clearing the mark would let a loop of short
1044+
// runs defer the sentinel forever.
1045+
defer_policy_.reset();
10351046
return 0;
1047+
}
10361048

10371049
auto const e = completed_ops_.pop();
10381050
scheduler_op* op = ready_is_continuation(e) ? nullptr : ready_as_op(e);
@@ -1042,6 +1054,27 @@ reactor_scheduler::do_one(lock_type& lock, long timeout_us, context_type& ctx)
10421054
{
10431055
bool more_handlers = !completed_ops_.empty();
10441056

1057+
// Handlers queued here usually start the next I/O
1058+
// themselves, so running them first can save a reactor pass.
1059+
// Defer at most once in a row so reposting work cannot
1060+
// starve I/O. poll() and poll_one() don't defer: the reactor
1061+
// turn they would skip may be their last before returning.
1062+
if (task_deferred_)
1063+
{
1064+
task_deferred_ = false;
1065+
defer_policy_.on_deferred_turn(more_handlers);
1066+
}
1067+
else if (more_handlers && timeout_us != 0)
1068+
{
1069+
if (defer_policy_.may_defer())
1070+
{
1071+
task_deferred_ = true;
1072+
completed_ops_.push(&task_op_);
1073+
continue;
1074+
}
1075+
defer_policy_.on_polled_instead();
1076+
}
1077+
10451078
if (!more_handlers &&
10461079
outstanding_work_.load(std::memory_order_acquire) == 0)
10471080
{

‎test/unit/fault/kqueue_faults.cpp‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -329,14 +329,12 @@ struct kqueue_faults
329329

330330
void testRunLoopFaults()
331331
{
332-
// Nothing calls kevent between the constructor and the run
333-
// loop's first wait: posting the task does not interrupt a
334-
// reactor that is not running yet
335-
// (reactor_scheduler::wake_one_thread_and_unlock), so nth 1 is
336-
// that wait.
332+
// The run loop runs the posted task before its first wait, and
333+
// arming the delay triggers the user event, so nth 1 is that
334+
// trigger and nth 2 is the wait.
337335
{
338336
io_context ioc(kqueue);
339-
fault_scope f(sys::kevent, EINTR);
337+
fault_scope f(sys::kevent, EINTR, 2);
340338
bool done = false;
341339
auto body = [&]() -> capy::task<> {
342340
std::ignore =
@@ -352,7 +350,7 @@ struct kqueue_faults
352350
// Any other errno leaves run() through an exception
353351
// (kqueue_scheduler::run_task).
354352
io_context ioc(kqueue);
355-
fault_scope f(sys::kevent, EBADF);
353+
fault_scope f(sys::kevent, EBADF, 2);
356354
auto body = [&]() -> capy::task<> {
357355
std::ignore =
358356
co_await corosio::delay(std::chrono::milliseconds(1));
@@ -377,10 +375,9 @@ struct kqueue_faults
377375
{
378376
io_context ioc(kqueue);
379377
{
380-
// stop() is the one path that reaches NOTE_TRIGGER without
381-
// a reactor thread (reactor_scheduler::stop), and it
382-
// interrupts only on the transition, so each stop below is
383-
// one kevent.
378+
// stop() reaches NOTE_TRIGGER with no other kevent call in
379+
// between, and it interrupts only on the transition, so each
380+
// stop below is one kevent.
384381
fault_scope first(sys::kevent, EIO, 1);
385382
fault_scope second(sys::kevent, EIO, 2);
386383
ioc.stop();

‎test/unit/fault/reactor_faults.hpp‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,15 @@
2727
#include <boost/corosio/test/socket_pair.hpp>
2828
#include <boost/corosio/udp_socket.hpp>
2929
#include <boost/corosio/wait_type.hpp>
30+
#include <boost/capy/ex/async_waker.hpp>
31+
#include <boost/capy/ex/await_context.hpp>
3032
#include <boost/capy/ex/run_async.hpp>
3133
#include <boost/capy/task.hpp>
3234

3335
#include <array>
3436
#include <cerrno>
3537
#include <chrono>
38+
#include <coroutine>
3639
#include <stop_token>
3740
#include <system_error>
3841
#include <tuple>
@@ -84,6 +87,9 @@ struct reactor_common_faults
8487
static constexpr sys spec_write = sys::write;
8588
#endif
8689
static constexpr sys vec_write = is_kqueue ? sys::writev : sys::sendmsg;
90+
static constexpr sys wait_sys = is_select ? sys::select
91+
: is_kqueue ? sys::kevent
92+
: sys::epoll_wait;
8793

8894
static endpoint loopback()
8995
{
@@ -1034,6 +1040,164 @@ struct reactor_common_faults
10341040
#endif
10351041
}
10361042

1043+
// A handler that an I/O completion posts runs before the reactor is
1044+
// polled again, since that handler may start the next I/O itself.
1045+
void testPostedWakeRunsBeforeNextPoll()
1046+
{
1047+
io_context ioc(Backend);
1048+
auto [a, b] = test::must(test::make_socket_pair(ioc));
1049+
capy::async_waker waker;
1050+
unsigned at_read = 0;
1051+
unsigned at_wake = 0;
1052+
// Counts this thread's calls to the wait symbol (every kevent on
1053+
// kqueue); the one it would fail is never reached.
1054+
fault_scope f(wait_sys, EINTR, 1u << 30);
1055+
1056+
auto waiter = [&]() -> capy::task<> {
1057+
auto [ec] = co_await waker.wait();
1058+
BOOST_TEST(!ec);
1059+
at_wake = f.count();
1060+
};
1061+
auto reader = [&]() -> capy::task<> {
1062+
char buf[1];
1063+
auto [ec, n] = co_await b.read_some(capy::mutable_buffer(buf, 1));
1064+
BOOST_TEST(!ec);
1065+
at_read = f.count();
1066+
waker.wake();
1067+
};
1068+
auto writer = [&]() -> capy::task<> {
1069+
char const c = 'x';
1070+
auto [ec, n] = co_await a.write_some(capy::const_buffer(&c, 1));
1071+
BOOST_TEST(!ec);
1072+
};
1073+
capy::run_async(ioc.get_executor())(waiter());
1074+
capy::run_async(ioc.get_executor())(reader());
1075+
capy::run_async(ioc.get_executor())(writer());
1076+
ioc.run();
1077+
1078+
// The read parked, so a poll completed it.
1079+
BOOST_TEST(at_read > 0);
1080+
BOOST_TEST_EQ(at_wake, at_read);
1081+
}
1082+
1083+
// A run stopped while the sentinel was deferred still owes that
1084+
// poll, so the next run polls before a posted handler: a stop never
1085+
// grants a second deferral in a row.
1086+
void testStoppedDeferralPollsFirst()
1087+
{
1088+
io_context ioc(Backend);
1089+
auto stopper = [&]() -> capy::task<> {
1090+
ioc.stop();
1091+
co_return;
1092+
};
1093+
capy::run_async(ioc.get_executor())(stopper());
1094+
ioc.run();
1095+
ioc.restart();
1096+
1097+
// Counts this thread's calls to the wait symbol (every kevent on
1098+
// kqueue); the one it would fail is never reached.
1099+
fault_scope f(wait_sys, EINTR, 1u << 30);
1100+
unsigned at_run = 0;
1101+
auto probe = [&]() -> capy::task<> {
1102+
at_run = f.count();
1103+
co_return;
1104+
};
1105+
capy::run_async(ioc.get_executor())(probe());
1106+
ioc.run();
1107+
1108+
BOOST_TEST_EQ(at_run, 1u);
1109+
}
1110+
1111+
// A handler that restarts the context on every turn must not earn
1112+
// the sentinel a fresh deferral each time, or a parked read would
1113+
// wait for the handler to stop reposting.
1114+
void testRestartWhileRunningKeepsPolling()
1115+
{
1116+
struct yield_awaitable
1117+
{
1118+
capy::continuation c{};
1119+
1120+
bool await_ready() const noexcept
1121+
{
1122+
return false;
1123+
}
1124+
1125+
void await_suspend(
1126+
std::coroutine_handle<> h, capy::await_context const* ac)
1127+
{
1128+
c.h = h;
1129+
ac->executor.post(c);
1130+
}
1131+
1132+
void await_resume() noexcept {}
1133+
};
1134+
1135+
io_context ioc(Backend);
1136+
auto [a, b] = test::must(test::make_socket_pair(ioc));
1137+
constexpr int turns = 1000;
1138+
int spins = 0;
1139+
int spins_at_read = turns;
1140+
auto reader = [&]() -> capy::task<> {
1141+
char buf[1];
1142+
auto [ec, n] = co_await b.read_some(capy::mutable_buffer(buf, 1));
1143+
BOOST_TEST(!ec);
1144+
spins_at_read = spins;
1145+
};
1146+
auto writer = [&]() -> capy::task<> {
1147+
char const c = 'x';
1148+
auto [ec, n] = co_await a.write_some(capy::const_buffer(&c, 1));
1149+
BOOST_TEST(!ec);
1150+
};
1151+
auto spinner = [&]() -> capy::task<> {
1152+
for (; spins < turns; ++spins)
1153+
{
1154+
ioc.restart();
1155+
co_await yield_awaitable{};
1156+
}
1157+
};
1158+
capy::run_async(ioc.get_executor())(reader());
1159+
capy::run_async(ioc.get_executor())(writer());
1160+
capy::run_async(ioc.get_executor())(spinner());
1161+
ioc.run();
1162+
1163+
BOOST_TEST_LT(spins_at_read, turns);
1164+
}
1165+
1166+
// Pump idiom: post a stopper, run, restart. Each run must still let
1167+
// the reactor complete a parked read eventually.
1168+
void testStopPumpKeepsPolling()
1169+
{
1170+
io_context ioc(Backend);
1171+
auto [a, b] = test::must(test::make_socket_pair(ioc));
1172+
bool read_done = false;
1173+
auto reader = [&]() -> capy::task<> {
1174+
char buf[1];
1175+
auto [ec, n] = co_await b.read_some(capy::mutable_buffer(buf, 1));
1176+
BOOST_TEST(!ec);
1177+
read_done = true;
1178+
};
1179+
auto writer = [&]() -> capy::task<> {
1180+
char const c = 'x';
1181+
auto [ec, n] = co_await a.write_some(capy::const_buffer(&c, 1));
1182+
BOOST_TEST(!ec);
1183+
};
1184+
auto stopper = [&]() -> capy::task<> {
1185+
ioc.stop();
1186+
co_return;
1187+
};
1188+
capy::run_async(ioc.get_executor())(reader());
1189+
capy::run_async(ioc.get_executor())(writer());
1190+
int pumps = 0;
1191+
for (; pumps < 1000 && !read_done; ++pumps)
1192+
{
1193+
capy::run_async(ioc.get_executor())(stopper());
1194+
ioc.run();
1195+
ioc.restart();
1196+
}
1197+
BOOST_TEST(read_done);
1198+
BOOST_TEST_LT(pumps, 1000);
1199+
}
1200+
10371201
// Accepted and assigned sockets learn their family from the
10381202
// addresses the library already reads, so option calls never ask.
10391203
void testAdoptedSocketsKnowFamily()
@@ -1352,6 +1516,10 @@ struct reactor_common_faults
13521516
testSocketFamilyProbeFails();
13531517
testOpenedSocketKnowsFamily();
13541518
testAdoptedSocketsKnowFamily();
1519+
testPostedWakeRunsBeforeNextPoll();
1520+
testStoppedDeferralPollsFirst();
1521+
testRestartWhileRunningKeepsPolling();
1522+
testStopPumpKeepsPolling();
13551523
testDatagramFails();
13561524
}
13571525
};

0 commit comments

Comments
 (0)