From 08fb980ad26eafede58f534574644572bf605ff4 Mon Sep 17 00:00:00 2001 From: Kevin Wan Date: Tue, 13 Apr 2021 00:04:19 +0800 Subject: [PATCH] add syncx.Guard func (#620) --- core/syncx/barrier.go | 9 +++++++-- core/syncx/barrier_test.go | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/core/syncx/barrier.go b/core/syncx/barrier.go index f790bcfd..0a3c894c 100644 --- a/core/syncx/barrier.go +++ b/core/syncx/barrier.go @@ -9,7 +9,12 @@ type Barrier struct { // Guard guards the given fn on the resource. func (b *Barrier) Guard(fn func()) { - b.lock.Lock() - defer b.lock.Unlock() + Guard(&b.lock, fn) +} + +// Guard guards the given fn with lock. +func Guard(lock sync.Locker, fn func()) { + lock.Lock() + defer lock.Unlock() fn() } diff --git a/core/syncx/barrier_test.go b/core/syncx/barrier_test.go index 95cb7574..7e2426ef 100644 --- a/core/syncx/barrier_test.go +++ b/core/syncx/barrier_test.go @@ -38,3 +38,19 @@ func TestBarrierPtr_Guard(t *testing.T) { wg.Wait() assert.Equal(t, total, count) } + +func TestGuard(t *testing.T) { + const total = 10000 + var count int + var lock sync.Mutex + wg := new(sync.WaitGroup) + wg.Add(total) + for i := 0; i < total; i++ { + go Guard(&lock, func() { + count++ + wg.Done() + }) + } + wg.Wait() + assert.Equal(t, total, count) +}