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)
}
}
写入自己的博客中才能记得长久