File: flag.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 836 kB
  • sloc: makefile: 4
file content (41 lines) | stat: -rw-r--r-- 753 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package missinggo

import "sync"

// Flag represents a boolean value, that signals sync.Cond's when it changes.
// It's not concurrent safe by intention.
type Flag struct {
	Conds map[*sync.Cond]struct{}
	value bool
}

func (me *Flag) Set(value bool) {
	if value != me.value {
		me.broadcastChange()
	}
	me.value = value
}

func (me *Flag) Get() bool {
	return me.value
}

func (me *Flag) broadcastChange() {
	for cond := range me.Conds {
		cond.Broadcast()
	}
}

func (me *Flag) addCond(c *sync.Cond) {
	if me.Conds == nil {
		me.Conds = make(map[*sync.Cond]struct{})
	}
	me.Conds[c] = struct{}{}
}

// Adds the sync.Cond to all the given Flag's.
func AddCondToFlags(cond *sync.Cond, flags ...*Flag) {
	for _, f := range flags {
		f.addCond(cond)
	}
}