-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathsync_cond.go
More file actions
66 lines (59 loc) · 1.39 KB
/
sync_cond.go
File metadata and controls
66 lines (59 loc) · 1.39 KB
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
package main
import (
"fmt"
"sync"
"time"
)
// 示例来自https://stackoverflow.com/questions/36857167/how-to-correctly-use-sync-cond
func syncCondErr() {
m := sync.Mutex{}
c := sync.NewCond(&m)
go func() {
time.Sleep(1 * time.Second)
c.Broadcast()
}()
m.Lock()
time.Sleep(2 * time.Second)
c.Wait()
}
func syncCondExplain() {
m := sync.Mutex{}
c := sync.NewCond(&m)
// Tip: 主协程先获得锁
c.L.Lock()
go func() {
// Tip: 协程一开始无法获得锁
c.L.Lock()
defer c.L.Unlock()
fmt.Println("3. 该协程获得了锁")
time.Sleep(2 * time.Second)
// Tip: 通过notify进行广播通知
c.Broadcast()
fmt.Println("4. 该协程执行完毕,即将执行defer中的解锁操作")
}()
fmt.Println("1. 主协程获得锁")
time.Sleep(1 * time.Second)
fmt.Println("2. 主协程依旧抢占着锁获得锁")
// Tip: 看一下Wait的大致实现,可以了解到,它是先释放锁,直到收到了notify,又进行加锁
c.Wait()
// Tip: 记得释放锁
c.L.Unlock()
fmt.Println("Done")
}
func syncCond() {
lock := sync.Mutex{}
cond := sync.NewCond(&lock)
for i := 0; i < 5; i++ {
go func(i int) {
cond.L.Lock()
defer cond.L.Unlock()
cond.Wait()
fmt.Printf("No.%d Goroutine Receive\n", i)
}(i)
}
time.Sleep(time.Second)
cond.Broadcast()
//cond.Signal()
time.Sleep(time.Second)
}
// 拓展阅读: https://github.com/golang/go/issues/21165