From 1b73df77b61f038f6f4b4ee3e4e07b48f6f6dcea Mon Sep 17 00:00:00 2001 From: xfy Date: Tue, 14 Apr 2026 14:24:52 +0800 Subject: [PATCH] =?UTF-8?q?refactor(variable):=20=E5=B0=86=20PoolStats=20?= =?UTF-8?q?=E7=9A=84=20Mutex=20=E6=94=B9=E4=B8=BA=20atomic.Int64=20?= =?UTF-8?q?=E8=AE=A1=E6=95=B0=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用 sync/atomic 替代 sync.RWMutex,消除统计操作中的锁开销, 提升并发性能。保持 PoolStats 公开 API 不变(返回 plain int64)。 Co-Authored-By: Claude Opus 4.6 --- internal/variable/pool.go | 42 +++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/internal/variable/pool.go b/internal/variable/pool.go index 554ebe1..deac4bb 100644 --- a/internal/variable/pool.go +++ b/internal/variable/pool.go @@ -7,6 +7,7 @@ package variable import ( "sync" + "sync/atomic" "github.com/valyala/fasthttp" ) @@ -26,20 +27,26 @@ type PoolStats struct { } var ( - // stats 全局池统计信息 - stats PoolStats - // statsMu 保护统计信息的读写锁 - statsMu sync.RWMutex + // gets 从池中获取对象的次数 + gets atomic.Int64 + // puts 放回池中对象的次数 + puts atomic.Int64 + // newCount 调用 New 函数创建对象的次数 + newCount atomic.Int64 + // active 当前活跃对象数量(Gets - Puts) + active atomic.Int64 ) // GetStats 获取池统计信息的副本。 // // 返回当前统计信息的快照,线程安全。 func GetStats() PoolStats { - statsMu.RLock() - s := stats - statsMu.RUnlock() - return s + return PoolStats{ + Gets: gets.Load(), + Puts: puts.Load(), + NewCount: newCount.Load(), + Active: active.Load(), + } } // GetPool 获取底层的 sync.Pool(用于测试和调试)。 @@ -54,10 +61,8 @@ func PoolGet(ctx *fasthttp.RequestCtx) *Context { vc := NewContext(ctx) // 更新统计 - statsMu.Lock() - stats.Gets++ - stats.Active = stats.Gets - stats.Puts - statsMu.Unlock() + gets.Add(1) + active.Store(gets.Load() - puts.Load()) return vc } @@ -73,17 +78,16 @@ func PoolPut(vc *Context) { ReleaseContext(vc) // 更新统计 - statsMu.Lock() - stats.Puts++ - stats.Active = stats.Gets - stats.Puts - statsMu.Unlock() + puts.Add(1) + active.Store(gets.Load() - puts.Load()) } // ResetStats 重置统计信息。 // // 将所有统计计数器清零,线程安全。 func ResetStats() { - statsMu.Lock() - stats = PoolStats{} - statsMu.Unlock() + gets.Store(0) + puts.Store(0) + newCount.Store(0) + active.Store(0) }