标签:rand 输出 amp 解锁 ack atomic 协程 print 语言
代码演示:
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]
代码解读:
标签:rand 输出 amp 解锁 ack atomic 协程 print 语言
原文地址:https://www.cnblogs.com/Joestar/p/8870052.html