MacOS 和 Linux 上 go1.5beta2 的不同行为

该示例取自“围棋之旅”:https : //tour.golang.org/concurrency/1


显然,程序输出应该有 10 行:5 行代表“hello”,5 行代表“world”。


但我们有:


Linux - 9 行

MacOS - 10 行

Linux 输出(9 行):


$ go run 1.go 

hello

world

hello

world

hello

world

world

hello

hello

MacOS X 输出(10 行):


$ go run 1.go 

hello

world

world

hello

hello

world

hello

world

hello

world

任何人都可以解释 -为什么?


Linux uname -a:


Linux desktop 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1 (2015-05-24) x86_64 GNU/Linux

macOS uname -a:


Darwin 14.5.0 Darwin Kernel Version 14.5.0: Thu Jul  9 22:56:16 PDT 2015; root:xnu-2782.40.6~1/RELEASE_X86_64 x86_64

来自巡演的源代码:


package main


import (

    "fmt"

    "time"

)


func say(s string) {

    for i := 0; i < 5; i++ {

        time.Sleep(1000 * time.Millisecond)

        fmt.Println(s)

    }

}


func main() {

    go say("world")

    say("hello")

}


侃侃无极
浏览 182回答 1
1回答

慕工程0101907

从规范:程序执行首先初始化主包,然后调用函数main。当该函数调用返回时,程序退出。它不会等待其他(非main)goroutine 完成。所以不能保证 goroutine 打印"world"有时间在程序退出之前完成。我怀疑如果你运行程序足够多,你会在两个平台上看到 9 行和 10 行输出。将GOMAXPROCS环境变量设置为 2 也可能有助于触发问题。您可以通过使主 goroutine 显式等待另一个 goroutine 完成来修复它。例如,使用频道:func say(s string, done chan<- bool) {&nbsp; &nbsp; for i := 0; i < 5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(1000 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(s)&nbsp; &nbsp; }&nbsp; &nbsp; done <- true}func main() {&nbsp; &nbsp; c := make(chan bool, 2)&nbsp; &nbsp; go say("world", c)&nbsp; &nbsp; say("hello", c)&nbsp; &nbsp; <-c&nbsp; &nbsp; <-c}我已经向通道添加了一个缓冲区,以便say函数可以在不阻塞的情况下发送值(主要是为了"hello"调用实际返回)。然后我等待从通道接收两个值以确保两个调用都已完成。对于更复杂的程序,该sync.WaitGroup类型可以提供一种更方便的方式来等待多个 goroutine。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go