-
Notifications
You must be signed in to change notification settings - Fork 1
/
rwMutexSimple.go
78 lines (67 loc) · 1.73 KB
/
rwMutexSimple.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
package main
import (
"fmt"
"os"
"sync"
"time"
)
type secret struct {
RWM sync.RWMutex
password string
}
var Password = secret{password: "myPassword"}
func Change(c *secret, pass string) {
c.RWM.Lock()
fmt.Println("LChange")
time.Sleep(5 * time.Second)
c.password = pass
c.RWM.Unlock()
}
// The show function uses the `RLock()` and `RUnlock()` functions
// because its critical section is used for reading a shared variable.
// this will not block for multiple reading,
// but block the writing until all the reading `RUnlock`
func show(c *secret, i int) string {
c.RWM.RLock()
fmt.Println("show, reading by",i)
time.Sleep(2 * time.Second)
defer c.RWM.RUnlock()
return c.password
}
// showWithLock function uses an exclusive lock for reading,
// which means that only one showWithLock() function
// can read the password field of the secret structure at the same time.
// this is blocked both for reading, writing
func showWithLock(c *secret, i int) string {
c.RWM.Lock()
fmt.Println("showWithLock, reading by ",i )
time.Sleep(2 * time.Second)
defer c.RWM.Unlock()
return c.password
}
func main() {
var showFunction = func(c *secret, i int) string { return "" }
if len(os.Args) != 2 {
fmt.Println("Using sync.RWMutex!")
showFunction = show
} else {
fmt.Println("Using sync.Mutex!")
showFunction = showWithLock
}
var waitGroup sync.WaitGroup
fmt.Println("Pass:", showFunction(&Password, 0))
for i := 1; i < 15; i++ {
waitGroup.Add(1)
go func(i int) {
defer waitGroup.Done()
fmt.Println("Go Pass:", showFunction(&Password, i), "in index", i)
}(i)
}
go func() {
waitGroup.Add(1)
defer waitGroup.Done()
Change(&Password, "123456")
}()
waitGroup.Wait()
fmt.Println("Pass:", showFunction(&Password, 100))
}