-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathmutex.go
48 lines (41 loc) · 851 Bytes
/
mutex.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
package main
import (
"sync"
"time"
)
// code extracted by http://stackoverflow.com/questions/36167200/how-safe-are-golang-maps-for-concurrent-read-write-operations
var m = map[string]int{"a": 1}
var lock = sync.RWMutex{}
// read and write maps are not thread safe.
func main() {
go Read()
time.Sleep(1 * time.Second)
go Write()
time.Sleep(1 * time.Minute)
}
// Read reads an element of the map
func Read() {
for {
read()
}
}
// Write writes an element in the map
func Write() {
for {
write()
}
}
func read() {
// if you want to see the race condition,
// comment the lines below and run `go run -race mutex.go`
lock.RLock()
defer lock.RUnlock()
_ = m["a"]
}
func write() {
// if you want to see the race condition,
// comment the lines below and run `go run -race mutex.go`
lock.Lock()
defer lock.Unlock()
m["b"] = 2
}