move implementation to internal/ directory (#828)

This commit is contained in:
Christian Schwarz
2024-10-18 19:21:17 +02:00
committed by GitHub
parent b9b9ad10cf
commit 908807bd59
360 changed files with 507 additions and 507 deletions
+41
View File
@@ -0,0 +1,41 @@
package semaphore
import (
"context"
wsemaphore "golang.org/x/sync/semaphore"
"github.com/zrepl/zrepl/internal/daemon/logging/trace"
)
type S struct {
ws *wsemaphore.Weighted
}
func New(max int64) *S {
return &S{wsemaphore.NewWeighted(max)}
}
type AcquireGuard struct {
s *S
released bool
}
// The returned AcquireGuard is not goroutine-safe.
func (s *S) Acquire(ctx context.Context) (*AcquireGuard, error) {
defer trace.WithSpanFromStackUpdateCtx(&ctx)()
if err := s.ws.Acquire(ctx, 1); err != nil {
return nil, err
} else if err := ctx.Err(); err != nil {
return nil, err
}
return &AcquireGuard{s, false}, nil
}
func (g *AcquireGuard) Release() {
if g == nil || g.released {
return
}
g.released = true
g.s.ws.Release(1)
}
+52
View File
@@ -0,0 +1,52 @@
package semaphore
import (
"context"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zrepl/zrepl/internal/daemon/logging/trace"
)
func TestSemaphore(t *testing.T) {
const numGoroutines = 10
const concurrentSemaphore = 6
const sleepTime = 1 * time.Second
begin := time.Now()
sem := New(concurrentSemaphore)
var acquisitions struct {
beforeT, afterT uint32
}
rootCtx, endRoot := trace.WithTaskFromStack(context.Background())
defer endRoot()
_, add, waitEnd := trace.WithTaskGroup(rootCtx, "TestSemaphore")
for i := 0; i < numGoroutines; i++ {
// not capturing i so no need for local copy
add(func(ctx context.Context) {
res, err := sem.Acquire(ctx)
require.NoError(t, err)
defer res.Release()
if time.Since(begin) > sleepTime {
atomic.AddUint32(&acquisitions.afterT, 1)
} else {
atomic.AddUint32(&acquisitions.beforeT, 1)
}
time.Sleep(sleepTime)
})
}
waitEnd()
assert.True(t, acquisitions.beforeT == concurrentSemaphore)
assert.True(t, acquisitions.afterT == numGoroutines-concurrentSemaphore)
}