/
main.go
94 lines (84 loc) · 1.68 KB
/
main.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
// c := sync.NewCond(new(sync.Mutex))
c := newCond(new(sync.Mutex))
var wg sync.WaitGroup
wg.Add(3)
go func() {
defer wg.Done()
c.L.Lock()
c.Wait()
fmt.Println("go routine 1")
c.L.Unlock()
}()
go func() {
defer wg.Done()
c.L.Lock()
c.Wait()
fmt.Println("go routine 2")
c.L.Unlock()
}()
go func() {
defer wg.Done()
c.L.Lock()
c.Wait()
fmt.Println("go routine 3")
c.L.Unlock()
}()
time.Sleep(time.Second)
// c.Signal()
// c.Signal()
// c.Signal()
c.Broadcast()
wg.Wait()
}
func newCond(lock sync.Locker) cond {
return cond{L: lock}
}
// Taken from the source code from standard library sync.Cond
// ----------------------------------------------------------
// Cond implements a condition variable, a rendezvous point
// for goroutines waiting for or announcing the occurrence
// of an event.
//
// Each Cond has an associated Locker L (often a *Mutex or *RWMutex),
// which must be held when changing the condition and
// when calling the Wait method.
//
// A Cond must not be copied after first use.
type cond struct {
wait int32
notify int32
L sync.Locker
}
func (c *cond) Wait() {
t := atomic.AddInt32(&c.wait, 1) - 1
c.L.Unlock()
c.notifyListWait(t)
c.L.Lock()
}
func (c *cond) Signal() {
if atomic.LoadInt32(&c.notify) == atomic.LoadInt32(&c.wait) {
return
}
atomic.AddInt32(&c.notify, 1)
}
func (c *cond) Broadcast() {
if atomic.LoadInt32(&c.notify) == atomic.LoadInt32(&c.wait) {
return
}
atomic.StoreInt32(&c.notify, atomic.LoadInt32(&c.wait))
}
func (c *cond) notifyListWait(t int32) {
for {
if atomic.LoadInt32(&c.notify) > t {
return
}
}
}