锁,是操作系统的一种阻塞机制,为了保证数据在读写的过程中不被篡改。

互斥锁

同一时刻内,只允许一个goroutine对资源进行读写操作。

示例代码:

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

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

type Resource struct {
data int
mu sync.Mutex
}

func (r *Resource) Read() int {
r.mu.Lock()
defer r.mu.Unlock()
return r.data
}
func (r *Resource) Write(newdata int) {
r.mu.Lock()
defer r.mu.Unlock()
r.data = newdata
}
func main() {
r := &Resource{data: 100}
go func() {
for i := 0; i < 5; i++ {
fmt.Println(i, r.Read())
}
}()
go func() {
r.Write(666)
}()
time.Sleep(1 * time.Second)
}

读写锁

互斥锁的升级版,数据允许同一时刻被多个goroutine读取,只允许一个goroutine写入。目的是为了对于读需求比较多的业务,提高goroutines的并发效率。与互斥锁一样,写数据的过程中也是不允许其他goroutine进行读取操作的。

示例代码:

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

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

type Resource struct {
data int
mu sync.RWMutex
}

func (r *Resource) Read() int {
r.mu.RLock()
defer r.mu.RUnlock()
return r.data
}
func (r *Resource) Write(newdata int) {
r.mu.Lock()
defer r.mu.Unlock()
r.data = newdata
}
func main() {
r := &Resource{data: 100}
go func() {
for i := 0; i < 5; i++ {
fmt.Println(i, r.Read())
}
}()
go func() {
r.Write(666)
}()
time.Sleep(1 * time.Second)
}