2019-03-28 21:22:22 +01:00
|
|
|
package semaphore
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync/atomic"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2020-08-31 16:04:00 +02:00
|
|
|
|
2024-10-18 19:21:17 +02:00
|
|
|
"github.com/zrepl/zrepl/internal/daemon/logging/trace"
|
2019-03-28 21:22:22 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestSemaphore(t *testing.T) {
|
|
|
|
const numGoroutines = 10
|
2020-11-22 15:04:48 +01:00
|
|
|
const concurrentSemaphore = 6
|
2019-03-28 21:22:22 +01:00
|
|
|
const sleepTime = 1 * time.Second
|
|
|
|
|
|
|
|
begin := time.Now()
|
|
|
|
|
|
|
|
sem := New(concurrentSemaphore)
|
|
|
|
|
2020-02-23 23:24:12 +01:00
|
|
|
var acquisitions struct {
|
2019-03-28 21:22:22 +01:00
|
|
|
beforeT, afterT uint32
|
|
|
|
}
|
|
|
|
|
2020-11-22 15:04:48 +01:00
|
|
|
rootCtx, endRoot := trace.WithTaskFromStack(context.Background())
|
|
|
|
defer endRoot()
|
|
|
|
_, add, waitEnd := trace.WithTaskGroup(rootCtx, "TestSemaphore")
|
2020-04-11 15:49:41 +02:00
|
|
|
|
2019-03-28 21:22:22 +01:00
|
|
|
for i := 0; i < numGoroutines; i++ {
|
2020-11-22 15:04:48 +01:00
|
|
|
// not capturing i so no need for local copy
|
|
|
|
add(func(ctx context.Context) {
|
2020-04-11 15:49:41 +02:00
|
|
|
res, err := sem.Acquire(ctx)
|
2019-03-28 21:22:22 +01:00
|
|
|
require.NoError(t, err)
|
|
|
|
defer res.Release()
|
|
|
|
if time.Since(begin) > sleepTime {
|
2020-02-23 23:24:12 +01:00
|
|
|
atomic.AddUint32(&acquisitions.afterT, 1)
|
2020-11-22 15:04:48 +01:00
|
|
|
} else {
|
|
|
|
atomic.AddUint32(&acquisitions.beforeT, 1)
|
2019-03-28 21:22:22 +01:00
|
|
|
}
|
|
|
|
time.Sleep(sleepTime)
|
2020-11-22 15:04:48 +01:00
|
|
|
})
|
2019-03-28 21:22:22 +01:00
|
|
|
}
|
|
|
|
|
2020-11-22 15:04:48 +01:00
|
|
|
waitEnd()
|
2019-03-28 21:22:22 +01:00
|
|
|
|
2020-02-23 23:24:12 +01:00
|
|
|
assert.True(t, acquisitions.beforeT == concurrentSemaphore)
|
|
|
|
assert.True(t, acquisitions.afterT == numGoroutines-concurrentSemaphore)
|
2019-03-28 21:22:22 +01:00
|
|
|
|
|
|
|
}
|