其他分享
首页 > 其他分享> > go的sync.Mutex的锁的使用

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)
	}
}

标签:uint64,task,int,sync,var,Mutex,go
来源: https://www.cnblogs.com/heris/p/15967643.html