From 64ecd459a1b29a4dceadf9b09fad265e1043b5cf Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Mon, 21 Aug 2023 16:06:44 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20concurrent.Pool=20=E6=96=B0=E5=A2=9E=20?= =?UTF-8?q?EAC=20=E5=87=BD=E6=95=B0=EF=BC=8C=E7=94=A8=E4=BA=8E=E5=8A=A8?= =?UTF-8?q?=E6=80=81=E8=B0=83=E6=95=B4=E7=BC=93=E5=86=B2=E5=8C=BA=E5=A4=A7?= =?UTF-8?q?=E5=B0=8F=E3=80=82=E4=BC=98=E5=8C=96=E8=B6=85=E5=87=BA=E7=BC=93?= =?UTF-8?q?=E5=86=B2=E5=8C=BA=E5=A4=A7=E5=B0=8F=E8=AD=A6=E5=91=8A=E6=97=A5?= =?UTF-8?q?=E5=BF=97=EF=BC=8C=E5=A2=9E=E5=8A=A0=E5=A0=86=E6=A0=88=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=EF=BC=8C=E7=94=A8=E4=BA=8E=E5=AE=9A=E4=BD=8D=E9=AB=98?= =?UTF-8?q?=E9=A2=91=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/concurrent/pool.go | 22 ++++++++++++++++++---- utils/concurrent/pool_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 utils/concurrent/pool_test.go diff --git a/utils/concurrent/pool.go b/utils/concurrent/pool.go index 8f69150..79184c7 100644 --- a/utils/concurrent/pool.go +++ b/utils/concurrent/pool.go @@ -2,6 +2,7 @@ package concurrent import ( "github.com/kercylan98/minotaur/utils/log" + "go.uber.org/zap" "sync" ) @@ -27,7 +28,20 @@ type Pool[T any] struct { bufferSize int generator func() T releaser func(data T) - warn int + warn int64 +} + +// EAC 动态调整缓冲区大小,适用于突发场景使用 +// - 当 size <= 0 时,不进行调整 +// - 当缓冲区大小不足时,会导致大量的新对象生成、销毁,增加 GC 压力。此时应考虑调整缓冲区大小 +// - 当缓冲区大小过大时,会导致大量的对象占用内存,增加内存压力。此时应考虑调整缓冲区大小 +func (slf *Pool[T]) EAC(size int) { + if size <= 0 { + return + } + slf.mutex.Lock() + slf.bufferSize = size + slf.mutex.Unlock() } func (slf *Pool[T]) Get() T { @@ -38,10 +52,10 @@ func (slf *Pool[T]) Get() T { slf.mutex.Unlock() return data } - slf.mutex.Unlock() slf.warn++ - if slf.warn >= 100 { - log.Warn("Pool", log.String("Get", "the number of buffer members is insufficient, consider whether it is due to unreleased or inappropriate buffer size")) + slf.mutex.Unlock() + if slf.warn >= 256 { + log.Warn("Pool", log.String("Get", "the number of buffer members is insufficient, consider whether it is due to unreleased or inappropriate buffer size"), zap.Stack("stack")) slf.warn = 0 } return slf.generator() diff --git a/utils/concurrent/pool_test.go b/utils/concurrent/pool_test.go new file mode 100644 index 0000000..03410c8 --- /dev/null +++ b/utils/concurrent/pool_test.go @@ -0,0 +1,32 @@ +package concurrent_test + +import ( + "github.com/kercylan98/minotaur/utils/concurrent" + "github.com/kercylan98/minotaur/utils/times" + "testing" + "time" +) + +func TestPool_EAC(t *testing.T) { + var p = concurrent.NewPool[int](10, func() int { + return 0 + }, func(data int) { + }) + + go func() { + for i := 0; i < 1000; i++ { + go func() { + for { + p.Release(p.Get()) + } + }() + } + }() + + go func() { + time.Sleep(2 * time.Second) + p.EAC(2048) + }() + + time.Sleep(100 * times.Day) +}