Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

62 рядки
1.5 KiB

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