File: wait.go

package info (click to toggle)
gdu 5.34.2-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 1,288 kB
  • sloc: makefile: 145
file content (49 lines) | stat: -rw-r--r-- 889 bytes parent folder | download | duplicates (4)
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
42
43
44
45
46
47
48
49
package analyze

import "sync"

// A WaitGroup waits for a collection of goroutines to finish.
// In contrast to sync.WaitGroup Add method can be called from a goroutine.
type WaitGroup struct {
	wait   sync.Mutex
	value  int
	access sync.Mutex
}

// Init prepares the WaitGroup for usage, locks
func (s *WaitGroup) Init() *WaitGroup {
	s.wait.Lock()
	return s
}

// Add increments value
func (s *WaitGroup) Add(value int) {
	s.access.Lock()
	s.value += value
	s.access.Unlock()
}

// Done decrements the value by one, if value is 0, lock is released
func (s *WaitGroup) Done() {
	s.access.Lock()
	s.value--
	s.check()
	s.access.Unlock()
}

// Wait blocks until value is 0
func (s *WaitGroup) Wait() {
	s.access.Lock()
	isValue := s.value > 0
	s.access.Unlock()
	if isValue {
		s.wait.Lock()
	}
}

func (s *WaitGroup) check() {
	if s.value == 0 {
		s.wait.TryLock()
		s.wait.Unlock()
	}
}