mutexes _ golang

In the previous example we saw how to manage simple counter state using atomic operations. For more complex state we can use a mutex to safetly access data across multiple goroutines

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)
                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)
                val := rand.Intn(100)
                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:  4738109
state : map[0:40 2:43 3:90 1:13 4:7]

总结 :

  1: ...

本文来自:博客园

感谢作者:jackkiexu

查看原文:mutexes _ golang

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。