ModernUO/Projects/Server/EventLoopTasks.cs
Kamron Batman 6aedbbe2ef
perf(core): sleep the event loop when idle
The loop span through its body regardless of whether there was anything
to do -- ~10% of a desktop core for an empty shard, ~70% of a small VPS
core, and a process that never idles is exactly what burstable vCPU
plans throttle.

The loop now blocks in NetState.WaitForCompletion whenever every queue
it drains is empty, waking on the next timer tick or the moment work
arrives. Receive completions, new connections, and cross-thread
LoopContext.Post (via IORingGroup 1.0.10's sticky Wake) are all in the
wait set, so sleeping adds no latency to any of them; only timer-driven
logic sees wheel lag, bounded by server.eventLoopIdleWaitMs (default
2ms, 0 = never sleep).

Measured on a real world of 190k items / 33k mobiles: 10.4% of a core
to 0.8-1.0%, with peak tick lag unchanged. Spin mode independently
gained 7x the iterations per core from the ring's AcceptEx rework.
Sleeping also gives the GC natural pause points, which the old spin
loop denied it -- memory no longer climbs until a save forces a
collection.

A sleep is bounded by the next wheel turn, so a correctly honoured
sleep can never miss a deadline; the only way sleeping harms the wheel
is the host returning the wait late. That overshoot is measured on
every sleep, and an escalating backoff (server.lateWakeThreshold)
suspends sleeping when it persists -- server work like saves or heavy
commands cannot trip it by construction. Hosts without high-resolution
waits are detected once at startup and spin instead. The admin gump
shows the verdict instead of the now-meaningless CPS figure, which is
removed.

Time accounting for diagnosis is compiled out of normal builds: build
with -p:EventLoopProfiling=true to enable EventLoopProfiler (per-phase
wall time, sleep overshoot, GC pauses, stolen-time residual, ~15min
ring buffer) and the [LoopStats command with CSV dump. See
dev-docs/debugging-event-loop.md for the diagnosis funnel.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 12:53:48 -07:00

135 lines
4.1 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: EventLoopTasks.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace Server;
public sealed class EventLoopContext : SynchronizationContext
{
public enum Priority
{
Normal,
High
}
private readonly ConcurrentQueue<Action> _queue;
private readonly ConcurrentQueue<Action> _priorityQueue;
private readonly Thread _mainThread;
private readonly int _maxPerFrame;
public EventLoopContext(int maxPerFrame = 128)
{
_maxPerFrame = maxPerFrame;
_queue = [];
_priorityQueue = [];
_mainThread = Thread.CurrentThread;
}
public override SynchronizationContext CreateCopy() => new EventLoopContext();
/// <summary>
/// True when no callbacks are waiting to run.
/// </summary>
/// <remarks>
/// <see cref="ExecuteTasks"/> drains at most <c>_maxPerFrame</c> callbacks, so work can
/// legitimately be left over. The event loop checks this before sleeping so a backlog keeps
/// it running instead.
/// </remarks>
public bool IsEmpty => _queue.IsEmpty && _priorityQueue.IsEmpty;
public void Post(Action d, Priority priority = Priority.Normal)
{
(priority == Priority.High ? _priorityQueue : _queue).Enqueue(d);
WakeEventLoop();
}
public override void Post(SendOrPostCallback d, object state)
{
_queue.Enqueue(() => d(state));
WakeEventLoop();
}
/// <summary>
/// Nudges the game loop in case it is asleep: the loop blocks on network I/O, which a queue
/// push alone does not signal.
/// </summary>
private void WakeEventLoop()
{
// A post from the loop thread cannot need a wake -- the loop is executing this very call
// -- and the signal is a syscall on every backend.
if (Thread.CurrentThread == _mainThread)
{
EventLoopProfiler.WakeSignal(elided: true);
return;
}
EventLoopProfiler.WakeSignal(elided: false);
// Safe before networking is configured and after teardown; NetState.Wake does nothing.
Network.NetState.Wake();
}
public override void Send(SendOrPostCallback d, object state)
{
if (Thread.CurrentThread == _mainThread)
{
d(state);
return;
}
var evt = new AutoResetEvent(false);
_queue.Enqueue(() =>
{
d(state);
evt.Set();
});
WakeEventLoop();
evt.WaitOne();
}
public void ExecuteTasks()
{
if (Thread.CurrentThread != _mainThread)
{
throw new Exception("Called EventLoop.ExecuteTasks on incorrect thread!");
}
var count = _priorityQueue.Count;
for (var i = 0; i < count; i++)
{
if (_priorityQueue.TryDequeue(out var a))
{
a();
}
}
count = Math.Min(_queue.Count, _maxPerFrame);
for (var i = 0; i < count; i++)
{
if (_queue.TryDequeue(out var a))
{
a();
}
}
}
}