-
Notifications
You must be signed in to change notification settings - Fork 390
/
semaphore.go
45 lines (36 loc) · 955 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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information
package sync2
import (
"context"
"golang.org/x/sync/semaphore"
)
// Semaphore implements a closable semaphore
type Semaphore struct {
ctx context.Context
close func()
sema *semaphore.Weighted
}
// NewSemaphore creates a semaphore with the specified size.
func NewSemaphore(size int) *Semaphore {
sema := &Semaphore{}
sema.Init(size)
return sema
}
// Init initializes semaphore to the specified size.
func (sema *Semaphore) Init(size int) {
sema.ctx, sema.close = context.WithCancel(context.Background())
sema.sema = semaphore.NewWeighted(int64(size))
}
// Close closes the semaphore from further use.
func (sema *Semaphore) Close() {
sema.close()
}
// Lock locks the semaphore.
func (sema *Semaphore) Lock() bool {
return sema.sema.Acquire(sema.ctx, 1) == nil
}
// Unlock unlocks the semaphore.
func (sema *Semaphore) Unlock() {
sema.sema.Release(1)
}