flag.go 753 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package missinggo
  2. import "sync"
  3. // Flag represents a boolean value, that signals sync.Cond's when it changes.
  4. // It's not concurrent safe by intention.
  5. type Flag struct {
  6. Conds map[*sync.Cond]struct{}
  7. value bool
  8. }
  9. func (me *Flag) Set(value bool) {
  10. if value != me.value {
  11. me.broadcastChange()
  12. }
  13. me.value = value
  14. }
  15. func (me *Flag) Get() bool {
  16. return me.value
  17. }
  18. func (me *Flag) broadcastChange() {
  19. for cond := range me.Conds {
  20. cond.Broadcast()
  21. }
  22. }
  23. func (me *Flag) addCond(c *sync.Cond) {
  24. if me.Conds == nil {
  25. me.Conds = make(map[*sync.Cond]struct{})
  26. }
  27. me.Conds[c] = struct{}{}
  28. }
  29. // Adds the sync.Cond to all the given Flag's.
  30. func AddCondToFlags(cond *sync.Cond, flags ...*Flag) {
  31. for _, f := range flags {
  32. f.addCond(cond)
  33. }
  34. }