blob: fbe697c37684c3981be2fb18c03a4c2a371f4c7b [file] [log] [blame]
khenaidoo5fc5cea2021-08-11 17:39:16 -04001/*
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.
21package grpcsync
22
23import (
24 "sync"
25 "sync/atomic"
26)
27
28// Event represents a one-time event that may occur in the future.
29type Event struct {
30 fired int32
31 c chan struct{}
32 o sync.Once
33}
34
35// Fire causes e to complete. It is safe to call multiple times, and
36// concurrently. It returns true iff this call to Fire caused the signaling
37// channel returned by Done to close.
38func (e *Event) Fire() bool {
39 ret := false
40 e.o.Do(func() {
41 atomic.StoreInt32(&e.fired, 1)
42 close(e.c)
43 ret = true
44 })
45 return ret
46}
47
48// Done returns a channel that will be closed when Fire is called.
49func (e *Event) Done() <-chan struct{} {
50 return e.c
51}
52
53// HasFired returns true if Fire has been called.
54func (e *Event) HasFired() bool {
55 return atomic.LoadInt32(&e.fired) == 1
56}
57
58// NewEvent returns a new, ready-to-use Event.
59func NewEvent() *Event {
60 return &Event{c: make(chan struct{})}
61}