File: cond.go

package info (click to toggle)
docker.io 26.1.5%2Bdfsg1-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 68,576 kB
  • sloc: sh: 5,748; makefile: 912; ansic: 664; asm: 228; python: 162
file content (40 lines) | stat: -rw-r--r-- 770 bytes parent folder | download | duplicates (10)
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
package cond

import (
	"sync"
)

// NewStatefulCond returns a stateful version of sync.Cond . This cond will
// never block on `Wait()` if `Signal()` has been called after the `Wait()` last
// returned. This is useful for avoiding to take a lock on `cond.Locker` for
// signalling.
func NewStatefulCond(l sync.Locker) *StatefulCond {
	sc := &StatefulCond{main: l}
	sc.c = sync.NewCond(&sc.mu)
	return sc
}

type StatefulCond struct {
	main      sync.Locker
	mu        sync.Mutex
	c         *sync.Cond
	signalled bool
}

func (s *StatefulCond) Wait() {
	s.main.Unlock()
	s.mu.Lock()
	if !s.signalled {
		s.c.Wait()
	}
	s.signalled = false
	s.mu.Unlock()
	s.main.Lock()
}

func (s *StatefulCond) Signal() {
	s.mu.Lock()
	s.signalled = true
	s.c.Signal()
	s.mu.Unlock()
}