Debian Codegraph @

api/v1/lib/extras/latch/latch.go

raw symbols SCIP
1 package latch
2
3 import "sync/atomic"
4
5 // Interface funcs are safe to invoke concurrently.
6 type Interface interface {
7 // Done returns a chan that blocks until Close is called. It never returns data.
8 Done() <-chan struct{}
9 // Close closes the latch; all future calls to Closed return true. Safe to invoke multiple times.
10 Close()
11 // Closed returns false while the latch is "open" and true after it has been closed via Close.
12 Closed() bool
13 }
14
15 type L struct {
16 value int32
17 line chan struct{}
18 }
19
20 // New returns a new "open" latch such that Closed returns false until Close is invoked.
21 func New() Interface {
22 return new(L).Reset()
23 }
24
25 func (l *L) Done() <-chan struct{} { return l.line }
26
27 // Close may panic for an uninitialized L
28 func (l *L) Close() {
29 if atomic.AddInt32(&l.value, 1) == 1 {
30 close(l.line)
31 }
32 <-l.line // concurrent calls to Close block until the latch is actually closed
33 }
34
35 func (l *L) Closed() (result bool) {
36 select {
37 case <-l.line:
38 result = true
39 default:
40 }
41 return
42 }
43
44 // Reset clears the state of the latch, not safe to execute concurrently with other L methods.
45 func (l *L) Reset() *L {
46 l.line, l.value = make(chan struct{}), 0
47 return l
48 }