forked from jincheng9/go-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rwmutex.go
53 lines (47 loc) · 868 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
package main
import (
"fmt"
"sync"
)
type Counter struct {
/*
成员count:计数器
成员rw: 读写锁,用于实现count的读写并发安全
*/
count int
rw sync.RWMutex
}
func (c *Counter) getCounter() int{
/*
读数据的时候加读锁
*/
c.rw.RLock()
defer c.rw.RUnlock()
return c.count
}
func (c *Counter) add() {
/*
写数据的时候加写锁
*/
c.rw.Lock()
defer c.rw.Unlock()
c.count++
}
func main() {
var wg sync.WaitGroup
size := 100
wg.Add(size)
var c Counter
/*
开启size个goroutine对变量c的数据成员count同时进行读写操作
*/
for i:=0; i<size; i++ {
go func() {
defer wg.Done()
c.getCounter()
c.add()
}()
}
wg.Wait()
fmt.Println("count=", c.count)
}