1 回答
TA贡献1836条经验 获得超4个赞
该for {}语句是一个无限循环,它独占一个处理器。设置runtime.GOMAXPROCS为 2 或更多以允许计时器运行。
例如,
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
fmt.Println(runtime.GOMAXPROCS(0))
runtime.GOMAXPROCS(runtime.NumCPU())
fmt.Println(runtime.GOMAXPROCS(0))
sleepChan := make(chan int)
go sleep(sleepChan)
select {
case sleepResult := <-sleepChan:
fmt.Println(sleepResult)
case <-time.After(time.Second):
fmt.Println("timed out")
}
busyChan := make(chan int)
go busyWait(busyChan)
select {
case busyResult := <-busyChan:
fmt.Println(busyResult)
case <-time.After(time.Second):
fmt.Println("timed out")
}
}
func sleep(c chan<- int) {
time.Sleep(10 * time.Second)
c <- 0
}
func busyWait(c chan<- int) {
for {
}
c <- 0
}
输出(4 CPU 处理器):
1
4
timed out
timed out
- 1 回答
- 0 关注
- 182 浏览
添加回答
举报