From fb0455250db567d3f8103bc729d3ce25a9d3190f Mon Sep 17 00:00:00 2001 From: Sydonian <794346190@qq.com> Date: Fri, 27 Dec 2024 15:20:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96sync2=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/sync2/bucket_pool.go | 74 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 utils/sync2/bucket_pool.go diff --git a/utils/sync2/bucket_pool.go b/utils/sync2/bucket_pool.go new file mode 100644 index 0000000..2551a42 --- /dev/null +++ b/utils/sync2/bucket_pool.go @@ -0,0 +1,74 @@ +package sync2 + +import "sync" + +type BucketPool[T any] struct { + empty []T + filled []T + emptyCond *sync.Cond + filledCond *sync.Cond +} + +func NewBucketPool[T any]() *BucketPool[T] { + return &BucketPool[T]{ + emptyCond: sync.NewCond(&sync.Mutex{}), + filledCond: sync.NewCond(&sync.Mutex{}), + } +} + +func (p *BucketPool[T]) GetEmpty() (T, bool) { + p.emptyCond.L.Lock() + defer p.emptyCond.L.Unlock() + + if len(p.empty) == 0 { + p.emptyCond.Wait() + } + + if len(p.empty) == 0 { + var t T + return t, false + } + + t := p.empty[0] + p.empty = p.empty[1:] + return t, true +} + +func (p *BucketPool[T]) PutEmpty(t T) { + p.emptyCond.L.Lock() + defer p.emptyCond.L.Unlock() + + p.empty = append(p.empty, t) + p.emptyCond.Signal() +} + +func (p *BucketPool[T]) GetFilled() (T, bool) { + p.filledCond.L.Lock() + defer p.filledCond.L.Unlock() + + if len(p.filled) == 0 { + p.filledCond.Wait() + } + + if len(p.filled) == 0 { + var t T + return t, false + } + + t := p.filled[0] + p.filled = p.filled[1:] + return t, true +} + +func (p *BucketPool[T]) PutFilled(t T) { + p.filledCond.L.Lock() + defer p.filledCond.L.Unlock() + + p.filled = append(p.filled, t) + p.filledCond.Signal() +} + +func (p *BucketPool[T]) WakeUpAll() { + p.emptyCond.Broadcast() + p.filledCond.Broadcast() +}