forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ongoing_work_limiter.go
35 lines (30 loc) · 987 Bytes
/
ongoing_work_limiter.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
package libkbfs
import "context"
// OngoingWorkLimiter limits maximum number of routines that can work on a same
// type of thing at the same time. For example, it can be used for limiting
// number of ongoing rekeys.
type OngoingWorkLimiter struct {
permits chan struct{}
}
// NewOngoingWorkLimiter creates a new *OngoingWorkLimiter with capacity of
// maxNumOngoingWorks.
func NewOngoingWorkLimiter(maxNumOngoingWorks int) *OngoingWorkLimiter {
return &OngoingWorkLimiter{
permits: make(chan struct{}, maxNumOngoingWorks),
}
}
// WaitToStart blocks until the limiter would allow one more routine to start
// working on the thing.
func (owl *OngoingWorkLimiter) WaitToStart(ctx context.Context) error {
select {
case owl.permits <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Done tells the limiter that the caller is done working on the thing, and
// somebody else is free to start work.
func (owl *OngoingWorkLimiter) Done() {
<-owl.permits
}