add syncx.Guard func (#620)
This commit is contained in:
@@ -9,7 +9,12 @@ type Barrier struct {
|
|||||||
|
|
||||||
// Guard guards the given fn on the resource.
|
// Guard guards the given fn on the resource.
|
||||||
func (b *Barrier) Guard(fn func()) {
|
func (b *Barrier) Guard(fn func()) {
|
||||||
b.lock.Lock()
|
Guard(&b.lock, fn)
|
||||||
defer b.lock.Unlock()
|
}
|
||||||
|
|
||||||
|
// Guard guards the given fn with lock.
|
||||||
|
func Guard(lock sync.Locker, fn func()) {
|
||||||
|
lock.Lock()
|
||||||
|
defer lock.Unlock()
|
||||||
fn()
|
fn()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,3 +38,19 @@ func TestBarrierPtr_Guard(t *testing.T) {
|
|||||||
wg.Wait()
|
wg.Wait()
|
||||||
assert.Equal(t, total, count)
|
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)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user