Golang中我們使用Channel或者sync.Mutex等鎖保護(hù)數(shù)據(jù),有沒(méi)有一種機(jī)制可以檢測(cè)代碼中的數(shù)據(jù)競(jìng)爭(zhēng)呢?
背景知識(shí)
數(shù)據(jù)競(jìng)爭(zhēng)是并發(fā)情況下,存在多線程/協(xié)程讀寫(xiě)相同數(shù)據(jù)的情況,必須存在至少一方寫(xiě)。另外,全是讀的情況下是不存在數(shù)據(jù)競(jìng)爭(zhēng)的。
使用race檢測(cè)數(shù)據(jù)競(jìng)爭(zhēng)
go build有個(gè)標(biāo)記race可以幫助檢測(cè)代碼中的數(shù)據(jù)競(jìng)爭(zhēng)。
? awesome git:(master) ? go help build
//.... omit
-race
enable data race detection.
Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64.
下面舉個(gè)栗子:
package main
import "fmt"
func main() {
i := 0
go func() {
i++ // write i
}()
fmt.Println(i) // read i
}
測(cè)試方法:
? awesome git:(master) ? go build -race hi.go
? awesome git:(master) ? ./hi
0
==================
WARNING: DATA RACE
Write at 0x00c00009c008 by goroutine 6:
main.main.func1()
/Users/mac/go/src/github.com/mac/awesome/hi.go:9 +0x4e
Previous read at 0x00c00009c008 by main goroutine:
main.main()
/Users/mac/go/src/github.com/mac/awesome/hi.go:12 +0x88
Goroutine 6 (running) created at:
main.main()
/Users/mac/go/src/github.com/mac/awesome/hi.go:8 +0x7a
==================
Found 1 data race(s)
exit status 66
提示示例代碼存在1處數(shù)據(jù)競(jìng)爭(zhēng),說(shuō)明了數(shù)據(jù)會(huì)在第9行寫(xiě),并且同時(shí)會(huì)在12行讀形成了數(shù)據(jù)競(jìng)爭(zhēng)。
當(dāng)然你也可以使用go run一步到位:
? awesome git:(master) ? go run -race hi.go
0
==================
WARNING: DATA RACE
Write at 0x00c000094008 by goroutine 6:
main.main.func1()
/Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go:9 +0x4e
Previous read at 0x00c000094008 by main goroutine:
main.main()
/Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go:12 +0x88
Goroutine 6 (running) created at:
main.main()
/Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go:8 +0x7a
==================
Found 1 data race(s)
exit status 66
如果這篇文章對(duì)你有幫助,請(qǐng)點(diǎn)個(gè)贊/喜歡,讓我知道我的寫(xiě)作是有價(jià)值的,感謝。