/
semaphore.go
48 lines (40 loc) · 996 Bytes
/
semaphore.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package concurrent
import (
"context"
"errors"
"golang.org/x/sync/semaphore"
)
type Semaphore struct {
w *semaphore.Weighted
}
func (s *Semaphore) SpawnContext(ctx context.Context, fn func(ctx context.Context) error) error {
if err := s.w.Acquire(ctx, 1); err != nil {
return err
}
defer s.w.Release(1)
return fn(ctx)
}
func (s *Semaphore) Spawn(fn func() error) error {
if err := s.w.Acquire(context.Background(), 1); err != nil {
return err
}
defer s.w.Release(1)
return fn()
}
func (s *Semaphore) TrySpawnContext(ctx context.Context, fn func(ctx context.Context) error) error {
if !s.w.TryAcquire(1) {
return errors.New("err: try acquire semaphore failed")
}
defer s.w.Release(1)
return fn(ctx)
}
func (s *Semaphore) TrySpawn(fn func() error) error {
if !s.w.TryAcquire(1) {
return errors.New("err: try acquire semaphore failed")
}
defer s.w.Release(1)
return fn()
}
func NewSemaphore(n int64) *Semaphore {
return &Semaphore{w: semaphore.NewWeighted(n)}
}