gpt4 book ai didi

concurrency - 为什么这个程序在我的系统上终止而不是在 Playground 上?

转载 作者:IT王子 更新时间:2023-10-29 00:49:48 27 4
gpt4 key购买 nike

考虑这个程序:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com