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: ...
有疑问加站长微信联系(非本文作者)