Skip to content

Commit

Permalink
add syncx.Guard func (zeromicro#620)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan authored Apr 12, 2021
1 parent b94d7aa commit 08fb980
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
9 changes: 7 additions & 2 deletions core/syncx/barrier.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
16 changes: 16 additions & 0 deletions core/syncx/barrier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 08fb980

Please sign in to comment.