From 52f7f3d174cab70e10ec48a1f4a862a179ae5184 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 9 Jan 2026 10:35:22 +0000 Subject: [PATCH] Optimize with double-checked locking for better concurrency Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com> --- proxy/wireguard/server.go | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/proxy/wireguard/server.go b/proxy/wireguard/server.go index c124c1ee..989abd54 100644 --- a/proxy/wireguard/server.go +++ b/proxy/wireguard/server.go @@ -83,18 +83,26 @@ func (*Server) Network() []net.Network { // Process implements proxy.Inbound. func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error { - // Use RWMutex to safely handle concurrent access to routing info + // Use double-checked locking to safely handle concurrent access to routing info // Only update if not set or if dispatcher is different - s.infoMutex.Lock() - if s.info.dispatcher == nil || s.info.dispatcher != dispatcher { - s.info = routingInfo{ - ctx: ctx, - dispatcher: dispatcher, - inboundTag: session.InboundFromContext(ctx), - contentTag: session.ContentFromContext(ctx), + // First check without write lock for better concurrency + s.infoMutex.RLock() + needsUpdate := s.info.dispatcher == nil || s.info.dispatcher != dispatcher + s.infoMutex.RUnlock() + + if needsUpdate { + s.infoMutex.Lock() + // Double-check after acquiring write lock + if s.info.dispatcher == nil || s.info.dispatcher != dispatcher { + s.info = routingInfo{ + ctx: ctx, + dispatcher: dispatcher, + inboundTag: session.InboundFromContext(ctx), + contentTag: session.ContentFromContext(ctx), + } } + s.infoMutex.Unlock() } - s.infoMutex.Unlock() ep, err := s.bindServer.ParseEndpoint(conn.RemoteAddr().String()) if err != nil {