1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-08 14:24:36 -04:00
v2fly/common/signal/notifier.go

48 lines
907 B
Go
Raw Normal View History

package signal
2018-06-26 09:04:47 -04:00
import "sync"
2018-04-02 03:52:16 -04:00
// Notifier is a utility for notifying changes. The change producer may notify changes multiple time, and the consumer may get notified asynchronously.
type Notifier struct {
2018-06-26 09:04:47 -04:00
sync.Mutex
waiters []chan struct{}
notCosumed bool
}
2018-02-11 17:28:42 -05:00
// NewNotifier creates a new Notifier.
func NewNotifier() *Notifier {
2018-06-26 09:04:47 -04:00
return &Notifier{}
}
2018-02-11 17:28:42 -05:00
// Signal signals a change, usually by producer. This method never blocks.
func (n *Notifier) Signal() {
2018-06-26 09:04:47 -04:00
n.Lock()
defer n.Unlock()
if len(n.waiters) == 0 {
n.notCosumed = true
return
}
2018-06-26 09:04:47 -04:00
for _, w := range n.waiters {
close(w)
}
2018-06-26 09:04:47 -04:00
n.waiters = make([]chan struct{}, 0, 8)
}
// Wait returns a channel for waiting for changes.
2018-02-08 09:39:46 -05:00
func (n *Notifier) Wait() <-chan struct{} {
2018-06-26 09:04:47 -04:00
n.Lock()
defer n.Unlock()
w := make(chan struct{})
if n.notCosumed {
n.notCosumed = false
close(w)
return w
}
2018-06-26 09:04:47 -04:00
n.waiters = append(n.waiters, w)
return w
}