请讲解runtime.GOMAXPROCS()

来源:10-2 go语言的调度器

CYW好好学习

2019-08-30

package main
import (
	"fmt"
	"runtime"
)

func main() {
	n:= runtime.GOMAXPROCS(1000)
	fmt.Println("n = ",n)
	for{go fmt.Print(1)
		fmt.Print(0)
	}
}

请问runtime.GOMAXPROCS()是怎用的?里面传什么参数,返回的又是什么?我听别人说参数是指定的CPU核数,但我试了参数可以传成千上万,所以请老师详解这个runtime.GOMAXPROCS,谢谢。

写回答

1回答

ccmouse

2019-09-08

文档上这样说:

GOMAXPROCS sets the maximum number of CPUs that can be executing simultaneously and returns the previous setting. If n < 1, it does not change the current setting. The number of logical CPUs on the local machine can be queried with NumCPU. This call will go away when the scheduler improves.

传的是你想同时使用的CPU的数量。一般这里传CPU的核数。那这个数如果传很大会怎样,文档也没说,但是说了可以通过NumCPU来获得CPU的数量。

所以呢,传很大它怎么表现,无所谓,很可能就是相当于传了实际的核的数量。如果的确纠结这一点,可以用NumCPU来查询到底几个核然后传入。

而且文档里也说了这个函数很有可能会拿掉,实际上现在的Go语言默认的GOMAXPROCS已经是CPU的核数了。

1
1
wlxz
意思 就是,电脑有几核的CPU,现在Go就默认使用几核了
2020-02-01
共1条回复

Google资深工程师深度讲解Go语言 由浅入深掌握Go语言

语法+分布式爬虫实战 为转型工程师量身打造

5995 学习 · 1909 问题

查看课程