duanbei1598
2013-12-14 13:47
浏览 50
已采纳

为什么该程序在我的系统上终止而不在操场上终止?

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?

图片转代码服务由CSDN问答提供 功能建议

请考虑以下程序:

  package main 
 
import  “ fmt” 
import“ time” 
import“ runtime” 
 
func main(){
 
x:= 0 
 
 go func(){
 time.Sleep(500 * time.Millisecond)\  nx = 1 
}()
 
 x == 0 {
 runtime.Gosched()
} 
 
 fmt.Println(“ it works!”)
} 
   
 
 

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duankan8739 2013-12-14 20:54
    已采纳

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

    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.

    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.

    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.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题