cond的使用方式不太好理解,我尝试用短跑运动解释一下,但最好用下面的代码跑跑会理解的更快。

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
package main

import (
"fmt"
"sync"
"time"
)

var sharedRsc = false

func main() {
var wg sync.WaitGroup
wg.Add(2)
m := sync.Mutex{}
c := sync.NewCond(&m)

//运动员1
go func() {
// this go routine wait for changes to the sharedRsc
c.L.Lock()
fmt.Println("goroutine1 pass Lock")
for sharedRsc == false {
fmt.Println("goroutine1 wait")
c.Wait()
}
fmt.Println("goroutine1", sharedRsc)
c.L.Unlock()
wg.Done()
}()

//运动员2
go func() {
// this go routine wait for changes to the sharedRsc
c.L.Lock()
fmt.Println("goroutine2 pass Lock")
for sharedRsc == false {
fmt.Println("goroutine2 wait")
c.Wait()
}
fmt.Println("goroutine2", sharedRsc)
c.L.Unlock()
wg.Done()
}()


time.Sleep(2 * time.Second)
c.L.Lock()
fmt.Println("main goroutine ready")
sharedRsc = true
c.Broadcast()
fmt.Println("main goroutine broadcast")
c.L.Unlock()
wg.Wait()
}