| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 1 | // Copyright 2021 The etcd Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package notify |
| 16 | |
| 17 | import ( |
| 18 | "sync" |
| 19 | ) |
| 20 | |
| 21 | // Notifier is a thread safe struct that can be used to send notification about |
| 22 | // some event to multiple consumers. |
| 23 | type Notifier struct { |
| 24 | mu sync.RWMutex |
| 25 | channel chan struct{} |
| 26 | } |
| 27 | |
| 28 | // NewNotifier returns new notifier |
| 29 | func NewNotifier() *Notifier { |
| 30 | return &Notifier{ |
| 31 | channel: make(chan struct{}), |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // Receive returns channel that can be used to wait for notification. |
| 36 | // Consumers will be informed by closing the channel. |
| 37 | func (n *Notifier) Receive() <-chan struct{} { |
| 38 | n.mu.RLock() |
| 39 | defer n.mu.RUnlock() |
| 40 | return n.channel |
| 41 | } |
| 42 | |
| 43 | // Notify closes the channel passed to consumers and creates new channel to used |
| 44 | // for next notification. |
| 45 | func (n *Notifier) Notify() { |
| 46 | newChannel := make(chan struct{}) |
| 47 | n.mu.Lock() |
| 48 | channelToClose := n.channel |
| 49 | n.channel = newChannel |
| 50 | n.mu.Unlock() |
| 51 | close(channelToClose) |
| 52 | } |