package main
import (
"fmt"
"runtime"
"sync"
"time"
)
//
//func test(){
// for i:=1;i<10;i++{
// fmt.Println("hello world"+ strconv.Itoa(i))
// time.Sleep(time.Second)
// }
//}
var(
myMap=make(map[int]int,10)
//lock全局互斥锁 synchornized
// mutex互斥
lock sync.Mutex
)
func test(n int ) {
res:=1
for i:=1;i<n;i++{
res*=i
}
//
lock.Lock()
myMap[n]=res
lock.Unlock()
}
// 全局变量加锁
//
func main() {
cpuNum:=runtime.NumCPU()
fmt.Println(cpuNum)
runtime.GOMAXPROCS(cpuNum-1)
for i:=1;i<=20;i++{
go test(i)
}
time.Sleep(time.Second*10)
lock.Lock()
for i,v:=range myMap{
fmt.Println(i,v)
}
lock.Unlock()
//go test()
//for i:=1;i<10;i++{
// fmt.Println("hello go"+ strconv.Itoa(i))
// time.Sleep(time.Second)
//}
}
go协程/goroutine
最新推荐文章于 2024-01-21 03:34:51 发布