go-zero/core/syncx/barrier_test.go

57 lines
897 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package syncx
import (
2020-10-13 19:29:20 +08:00
"sync"
2020-07-26 17:09:05 +08:00
"testing"
"github.com/stretchr/testify/assert"
)
func TestBarrier_Guard(t *testing.T) {
const total = 10000
var barrier Barrier
var count int
2020-10-13 19:29:20 +08:00
var wg sync.WaitGroup
wg.Add(total)
2020-07-26 17:09:05 +08:00
for i := 0; i < total; i++ {
2020-10-13 19:29:20 +08:00
go barrier.Guard(func() {
2020-07-26 17:09:05 +08:00
count++
2020-10-13 19:29:20 +08:00
wg.Done()
2020-07-26 17:09:05 +08:00
})
}
2020-10-13 19:29:20 +08:00
wg.Wait()
2020-07-26 17:09:05 +08:00
assert.Equal(t, total, count)
}
func TestBarrierPtr_Guard(t *testing.T) {
const total = 10000
barrier := new(Barrier)
var count int
2020-10-13 19:29:20 +08:00
wg := new(sync.WaitGroup)
wg.Add(total)
2020-07-26 17:09:05 +08:00
for i := 0; i < total; i++ {
2020-10-13 19:29:20 +08:00
go barrier.Guard(func() {
2020-07-26 17:09:05 +08:00
count++
2020-10-13 19:29:20 +08:00
wg.Done()
2020-07-26 17:09:05 +08:00
})
}
2020-10-13 19:29:20 +08:00
wg.Wait()
2020-07-26 17:09:05 +08:00
assert.Equal(t, total, count)
}
2021-04-13 00:04:19 +08:00
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)
}