golang map线程不安全 会竞争

package main

import (
	"fmt"
	"sync"
)

var (
	mp = make(map[int]uint64)
	wg sync.WaitGroup
	mux sync.Mutex
)

func main() {

	for i := 1; i <= 20; i++ {
		wg.Add(1)
		go test(i)
	}

	mux.Lock()


		fmt.Println(mp)


	mux.Unlock()
	wg.Wait()
}

func test(n int)  {
	wg.Done()
	var res uint64
	res = 1
	for i := 1; i <= n; i++ {
		res  = res * uint64(i)
	}
	mux.Lock()
	mp[n] = res
	mux.Unlock()
}

  

posted @ 2021-09-10 20:38  brady-wang  阅读(163)  评论(0编辑  收藏  举报