[GO]gomaxprocs的使用
package main import ( "runtime" "fmt" ) func main() { n := runtime.GOMAXPROCS(1)//指定使用核进行运算,这个函数的返回值是当前机器的cpu个数
fmt.Println(" n = ", n)
for true {
go fmt.Print(1)
fmt.Print(0)
}
}
会发现打印结果里有大片的1或者0
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
那如果指定两个核呢
... n := runtime.GOMAXPROCS(2) ...
那么结果会很不一样
1100011110010111001100101100010000001001111111000000011111110000011111100100001111100100000111111001011000000000000000000000000000000000000000000
可以看得出来并发的时间片出让明显快了很多
那么4核
n := runtime.GOMAXPROCS(4)
...
for true {
go fmt.Print(1)
go fmt.Print(2)
go fmt.Print(3)
fmt.Print(0)
}
...
虽然看不出来啥,
233123230003212132200000311131231231200023312231310002011331313330002222212132000003123131231231200123112323001131230002