| khenaidoo | ac63710 | 2019-01-14 15:44:34 -0500 | [diff] [blame] | 1 | /* |
| 2 | * |
| 3 | * Copyright 2018 gRPC authors. |
| 4 | * |
| 5 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | * you may not use this file except in compliance with the License. |
| 7 | * You may obtain a copy of the License at |
| 8 | * |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | * |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | * |
| 17 | */ |
| 18 | |
| 19 | // Package grpcsync implements additional synchronization primitives built upon |
| 20 | // the sync package. |
| 21 | package grpcsync |
| 22 | |
| 23 | import ( |
| khenaidoo | ac63710 | 2019-01-14 15:44:34 -0500 | [diff] [blame] | 24 | "sync/atomic" |
| 25 | ) |
| 26 | |
| 27 | // Event represents a one-time event that may occur in the future. |
| 28 | type Event struct { |
| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 29 | fired atomic.Bool |
| khenaidoo | ac63710 | 2019-01-14 15:44:34 -0500 | [diff] [blame] | 30 | c chan struct{} |
| khenaidoo | ac63710 | 2019-01-14 15:44:34 -0500 | [diff] [blame] | 31 | } |
| 32 | |
| 33 | // Fire causes e to complete. It is safe to call multiple times, and |
| 34 | // concurrently. It returns true iff this call to Fire caused the signaling |
| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 35 | // channel returned by Done to close. If Fire returns false, it is possible |
| 36 | // the Done channel has not been closed yet. |
| khenaidoo | ac63710 | 2019-01-14 15:44:34 -0500 | [diff] [blame] | 37 | func (e *Event) Fire() bool { |
| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 38 | if e.fired.CompareAndSwap(false, true) { |
| khenaidoo | ac63710 | 2019-01-14 15:44:34 -0500 | [diff] [blame] | 39 | close(e.c) |
| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 40 | return true |
| 41 | } |
| 42 | return false |
| khenaidoo | ac63710 | 2019-01-14 15:44:34 -0500 | [diff] [blame] | 43 | } |
| 44 | |
| 45 | // Done returns a channel that will be closed when Fire is called. |
| 46 | func (e *Event) Done() <-chan struct{} { |
| 47 | return e.c |
| 48 | } |
| 49 | |
| 50 | // HasFired returns true if Fire has been called. |
| 51 | func (e *Event) HasFired() bool { |
| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 52 | return e.fired.Load() |
| khenaidoo | ac63710 | 2019-01-14 15:44:34 -0500 | [diff] [blame] | 53 | } |
| 54 | |
| 55 | // NewEvent returns a new, ready-to-use Event. |
| 56 | func NewEvent() *Event { |
| 57 | return &Event{c: make(chan struct{})} |
| 58 | } |