go的sync.Mutex的锁的使用

点击查看代码
package main

import (
	"fmt"
	"sync"
	"time"
)

var (
	m = make(map[int]uint64)
	lock sync.Mutex
)

type task struct {
	n int
}

func calc(t *task) {
	var sum uint64
	sum = 1
	for i := 1; i <= t.n; i++ {
		sum *= uint64(i)
	}
	lock.Lock()
	m[t.n] = sum
	lock.Unlock()
}

func main() {
	for i := 0; i < 10; i++ {
		t := &task{n:i}
		go calc(t)
	}
	time.Sleep(1 * time.Second)

	lock.Lock()
	for k, v := range m {
		fmt.Printf("%d! = %v\n", k, v)
	}
}
posted @ 2022-03-05 12:51  ty1539  阅读(25)  评论(0编辑  收藏  举报