考虑这个程序:
package main
import "fmt"
import "time"
import "runtime"
func main() {
x := 0
go func() {
time.Sleep(500 * time.Millisecond)
x = 1
}()
for x == 0 {
runtime.Gosched()
}
fmt.Println("it works!")
}
为什么它在本地终止而不是在 Playground 上终止? ?我的程序终止是否依赖于未定义的行为?
最佳答案
Go playground 使用了 time.Sleep
的特殊实现,旨在防止个别程序独占网站的后端资源。
如 this article about the how the playground is implemented 中所述,调用 time.Sleep() 的 goroutines 进入休眠状态。 playground 后端一直等到所有其他 goroutine 都被阻塞(否则会出现死锁),然后以最短的超时时间唤醒 goroutine。
在您的程序中,您有两个 goroutine:主要的 goroutine 和调用 time.Sleep
的 goroutine。由于主 goroutine 从不阻塞,time.Sleep
调用永远不会返回。程序继续运行,直到超过分配给它的 CPU 时间,然后终止。
关于concurrency - 为什么这个程序在我的系统上终止而不是在 Playground 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20584078/