1 回答

TA貢獻1836條經(jīng)驗 獲得超4個贊
該for {}語句是一個無限循環(huán),它獨占一個處理器。設置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 關注
- 205 瀏覽
添加回答
舉報