037_go語言中的互斥鎖
阿新 • • 發佈:2018-04-17
tom fun highlight 代碼 brush 結果 runt math 沒有
代碼演示:
package main import ( "fmt" "math/rand" "runtime" "sync" "sync/atomic" "time" ) func main() { var state = make(map[int]int) var mutex = &sync.Mutex{} var ops int64 = 0 for r := 0; r < 100; r++ { go func() { total := 0 for { key := rand.Intn(5) + 1 mutex.Lock() total += state[key] mutex.Unlock() atomic.AddInt64(&ops, 1) runtime.Gosched() } }() } for w := 0; w < 10; w++ { go func() { for { key := rand.Intn(5) + 1 val := rand.Intn(100) + 1 mutex.Lock() state[key] = val mutex.Unlock() atomic.AddInt64(&ops, 1) runtime.Gosched() } }() } time.Sleep(time.Second) opsFinal := atomic.LoadInt64(&ops) fmt.Println("ops:", opsFinal) mutex.Lock() fmt.Println("state:", state) mutex.Unlock() }
代碼運行結果:
ops: 4728620 state: map[5:4 2:90 4:16 3:84 1:77]
代碼解讀:
- 互斥鎖用來使go協程間訪問數據更加安全,當一個數據上鎖之後,其它人就無法就該數據進行操作,一直到解鎖後
- 以上例子中,我們對state這個map進行了讀寫操作,並在讀寫過程中運用互斥鎖
- 本例中創建了一個讀的函數和一個寫的函數,均運用了互斥鎖
- 最終打印state時候,也上了鎖,這是因為,有可能協程還沒有讀寫完state,上鎖為了安全的輸出結果
037_go語言中的互斥鎖