一、介紹
sync.Mutex為互斥鎖(也叫全局鎖),Lock()加鎖,Unlock()解鎖。
二、場景
適用于場景: 讀寫次數(shù)不確定的場景(讀寫次數(shù)沒有明顯區(qū)別),同時只能一個讀或者寫
三、代碼測試
正確示范
package main
import (
"fmt"
"sync"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
for i := 0; i <= 100; i++ {
wg.Add(1)
go add(i)
}
wg.Wait()
}
var s = 1000
var lock sync.Mutex
var wg = &sync.WaitGroup{}
func add(count int) {
lock.Lock()
fmt.Printf("加鎖----第%d個攜程\n", count)
for i := 0; i < 4; i++ {
s++
fmt.Printf("j %d gorount %d \n", s, count)
}
fmt.Printf("解鎖----第%d個攜程\n", count)
wg.Done()
defer lock.Unlock()
}
運行命令:go run -race main.go 并未出現(xiàn)競爭
go run -race te.go
加鎖----第0個攜程
j 1001 gorount 0
j 1002 gorount 0
j 1003 gorount 0
j 1004 gorount 0
解鎖----第0個攜程
加鎖----第1個攜程
j 1005 gorount 1
j 1006 gorount 1
j 1007 gorount 1
j 1008 gorount 1
解鎖----第1個攜程
加鎖----第2個攜程
j 1009 gorount 2
j 1010 gorount 2
j 1011 gorount 2
j 1012 gorount 2
解鎖----第2個攜程
加鎖----第3個攜程
j 1013 gorount 3
j 1014 gorount 3
j 1015 gorount 3
j 1016 gorount 3
解鎖----第3個攜程
加鎖----第4個攜程
j 1017 gorount 4
j 1018 gorount 4
j 1019 gorount 4
j 1020 gorount 4
解鎖----第4個攜程
加鎖----第5個攜程
j 1021 gorount 5
j 1022 gorount 5
j 1023 gorount 5
j 1024 gorount 5
解鎖----第5個攜程
錯誤示范
此處注釋掉互斥鎖,增多協(xié)程數(shù)量為100
package main
import (
"fmt"
"sync"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
for i := 0; i <= 100; i++ {
wg.Add(1)
go add(i)
}
wg.Wait()
}
var s = 1000
var lock sync.Mutex
var wg = &sync.WaitGroup{}
func add(count int) {
//lock.Lock()
fmt.Printf("加鎖----第%d個攜程\n", count)
for i := 0; i < 4; i++ {
s++
fmt.Printf("j %d gorount %d \n", s, count)
}
fmt.Printf("解鎖----第%d個攜程\n", count)
wg.Done()
//defer lock.Unlock()
}
運行命令:go run -race main.go 出現(xiàn)競爭
解鎖----第53個攜程
==================
WARNING: DATA RACE
Read at 0x0000011e04b0 by goroutine 48:
main.add()
/Users/lee/goworkspace/src/th/mutex/main.go:27 +0xc9
Previous write at 0x0000011e04b0 by goroutine 54:
main.add()
/Users/lee/goworkspace/src/th/mutex/main.go:27 +0xe5
Goroutine 48 (running) created at:
main.main()
/Users/lee/goworkspace/src/th/mutex/main.go:13 +0x8c
Goroutine 54 (running) created at:
排解方法:
通過上述結(jié)果可以看出競爭出現(xiàn)的錯誤位置,方便我們?nèi)ソ鉀Q此類問題