mirror of
https://github.com/zrepl/zrepl.git
synced 2024-11-22 00:13:52 +01:00
parent
0d96627ffb
commit
c3d87289bb
@ -2,7 +2,6 @@ package semaphore
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@ -15,7 +14,7 @@ import (
|
|||||||
|
|
||||||
func TestSemaphore(t *testing.T) {
|
func TestSemaphore(t *testing.T) {
|
||||||
const numGoroutines = 10
|
const numGoroutines = 10
|
||||||
const concurrentSemaphore = 5
|
const concurrentSemaphore = 6
|
||||||
const sleepTime = 1 * time.Second
|
const sleepTime = 1 * time.Second
|
||||||
|
|
||||||
begin := time.Now()
|
begin := time.Now()
|
||||||
@ -26,29 +25,26 @@ func TestSemaphore(t *testing.T) {
|
|||||||
beforeT, afterT uint32
|
beforeT, afterT uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := context.Background()
|
rootCtx, endRoot := trace.WithTaskFromStack(context.Background())
|
||||||
defer trace.WithTaskFromStackUpdateCtx(&ctx)()
|
defer endRoot()
|
||||||
|
_, add, waitEnd := trace.WithTaskGroup(rootCtx, "TestSemaphore")
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
wg.Add(numGoroutines)
|
|
||||||
for i := 0; i < numGoroutines; i++ {
|
for i := 0; i < numGoroutines; i++ {
|
||||||
go func() {
|
// not capturing i so no need for local copy
|
||||||
ctx, end := trace.WithTaskFromStack(ctx)
|
add(func(ctx context.Context) {
|
||||||
defer end()
|
|
||||||
defer wg.Done()
|
|
||||||
res, err := sem.Acquire(ctx)
|
res, err := sem.Acquire(ctx)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
defer res.Release()
|
defer res.Release()
|
||||||
if time.Since(begin) > sleepTime {
|
if time.Since(begin) > sleepTime {
|
||||||
atomic.AddUint32(&acquisitions.beforeT, 1)
|
|
||||||
} else {
|
|
||||||
atomic.AddUint32(&acquisitions.afterT, 1)
|
atomic.AddUint32(&acquisitions.afterT, 1)
|
||||||
|
} else {
|
||||||
|
atomic.AddUint32(&acquisitions.beforeT, 1)
|
||||||
}
|
}
|
||||||
time.Sleep(sleepTime)
|
time.Sleep(sleepTime)
|
||||||
}()
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
wg.Wait()
|
waitEnd()
|
||||||
|
|
||||||
assert.True(t, acquisitions.beforeT == concurrentSemaphore)
|
assert.True(t, acquisitions.beforeT == concurrentSemaphore)
|
||||||
assert.True(t, acquisitions.afterT == numGoroutines-concurrentSemaphore)
|
assert.True(t, acquisitions.afterT == numGoroutines-concurrentSemaphore)
|
||||||
|
Loading…
Reference in New Issue
Block a user