runtimeruntime
cpuCPUCPUgoroutinedefer
NumCPU
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println("cpus:", runtime.NumCPU())
fmt.Println("goroot:", runtime.GOROOT())
fmt.Println("archive:", runtime.GOOS)
}
运行结果:
GOMAXPROCS
Golangcpugoroutineruntime.GOMAXPROCS
package main
import (
"fmt"
"runtime"
)
func init() {
runtime.GOMAXPROCS(1)
}
func main() {
// 任务逻辑...
}
Gosched
goroutineCPUgoroutineGogoroutinegoroutinegoroutine
package main
import (
"fmt"
"runtime"
)
func init() {
runtime.GOMAXPROCS(1) //使用单核
}
func main() {
exit := make(chan int)
go func() {
defer close(exit)
go func() {
fmt.Println("b")
}()
}()
for i := 0; i < 4; i++ {
fmt.Println("a:", i)
if i == 1 {
runtime.Gosched() //切换任务
}
}
<-exit
}
结果:
使用多核测试:
package main
import (
"fmt"
"runtime"
)
func init() {
runtime.GOMAXPROCS(4) //使用多核
}
func main() {
exit := make(chan int)
go func() {
defer close(exit)
go func() {
fmt.Println("b")
}()
}()
for i := 0; i < 4; i++ {
fmt.Println("a:", i)
if i == 1 {
runtime.Gosched() //切换任务
}
}
<-exit
}
结果:
main
CPUIOCPU