Go Example--锁

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++ {
		//起100个协程
		go func() {
			total := 0
			for {
				key := rand.Intn(5)
				//读取map中的数据加锁
				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)
				//写入map中的数据加锁
				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)
	//加锁读取state的数据
	mutex.Lock()
	fmt.Println("state:", state)
	mutex.Unlock()
}
原文地址:https://www.cnblogs.com/promenader/p/9832366.html