golang 互斥鎖 sync.Mutex

一、介紹
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此類問題

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

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