/
rwMutex.go
59 lines (49 loc) · 939 Bytes
/
rwMutex.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
package main
import (
"fmt"
"sync"
"time"
)
var Password *secret
var wg sync.WaitGroup
type secret struct {
RWM sync.RWMutex
password string
}
func Change(pass string) {
fmt.Println("Change() function")
Password.RWM.Lock()
fmt.Println("Change() Locked")
time.Sleep(4 * time.Second)
Password.password = pass
Password.RWM.Unlock()
fmt.Println("Change() UnLocked")
}
func show() {
defer wg.Done()
Password.RWM.RLock()
fmt.Println("Show function locked!")
time.Sleep(2 * time.Second)
fmt.Println("Pass value:", Password.password)
defer Password.RWM.RUnlock()
}
func main() {
Password = &secret{password: "myPass"}
for i := 0; i < 3; i++ {
wg.Add(1)
go show()
}
wg.Add(1)
go func() {
defer wg.Done()
Change("123456")
}()
wg.Add(1)
go func() {
defer wg.Done()
Change("54321")
}()
wg.Wait()
// Direct access to Password.password
fmt.Println("Current password value:", Password.password)
}