Mat*_*iak 1 concurrency timeout go thread-sleep busy-waiting
在Go中,我可以time.After用来超时睡眠功能,但我不能对忙碌等待(或工作)的功能做同样的事情.以下代码timed out在一秒钟后返回,然后挂起.
package main
import (
"fmt"
"time"
)
func main() {
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
}
Run Code Online (Sandbox Code Playgroud)
为什么在第二种情况下超时没有触发,我需要用什么替代方法来中断工作goroutines?
该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
}
Run Code Online (Sandbox Code Playgroud)
输出(4个CPU处理器):
1
4
timed out
timed out
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |