輕松檢測(cè)Golang并發(fā)的數(shù)據(jù)競(jìng)爭(zhēng)

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à)值的,感謝。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容