为什么这个程序在我的系统上终止,但不在操场上? [英] Why does this program terminate on my system but not on playground?

查看:134
本文介绍了为什么这个程序在我的系统上终止,但不在操场上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Consider this program:

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!")
}

为什么它会在本地终止,而不是游乐场?我的程序的终止依赖于未定义的行为吗?

Why does it terminate locally but not on Playground? Does the termination of my program rely on undefined behavior?

推荐答案

该代码不提供太多保证。它几乎完全依赖未定义行为的实现细节。

That code doesn't offer much guarantees. It's relying almost entirely on implementation details around undefined behavior.

在大多数多线程系统中,不能保证一个线程中没有障碍的更改会在另一个线程中看到。你已经有了一个goroutine,它可以在另一个处理器上运行,完全写入一个值给任何人保证读取的变量。

In most multi-threaded systems, there's no guarantee that a change in one thread with no barrier will be seen in another. You've got a goroutine which could be running on another processor altogether writing a value to a variable nobody's ever guaranteed to read.

for x对于{,== 0 {可以很容易地重写为,因为永远不会保证对该变量的任何更改都可以看到。

The for x == 0 { could quite easily be rewritten to for { since there's never a guarantee any changes to that variable might be visible.

比赛探测器也可能会报告这个问题。你真的不应该期望这个工作。如果你想要一个 sync.WaitGroup ,你应该只使用一个,因为它正确地跨线程进行协调。

The race detector will also probably report this issue. You should really not expect this to work. If you want a sync.WaitGroup you should just use one as it properly coordinates across threads.

这篇关于为什么这个程序在我的系统上终止,但不在操场上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆