Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MacOS和Linux上go1.5beta2的不同行为_Linux_Macos_Go - Fatal编程技术网

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

MacOS和Linux上go1.5beta2的不同行为,linux,macos,go,Linux,Macos,Go,示例取自“围棋之旅”: 显然,程序输出应该有10行:5行表示“hello”,5行表示“world” 但我们有: Linux-9行 MacOS-10行 Linux输出(9行): MacOS X输出(10行): 谁能解释一下为什么 Linuxuname-a: Linux desktop 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1 (2015-05-24) x86_64 GNU/Linux Darwin 14.5.0 Darwin Kernel Ver

示例取自“围棋之旅”:

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

但我们有:

  • Linux-9行
  • MacOS-10行
Linux输出(9行):

MacOS X输出(10行):

谁能解释一下为什么

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
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
MacOS X
uname-a

Linux desktop 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1 (2015-05-24) x86_64 GNU/Linux
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
来自tour的源代码:

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")
}
主程序包
进口(
“fmt”
“时间”
)
func say(s字符串){
对于i:=0;i<5;i++{
时间。睡眠(1000*时间。毫秒)
fmt.Println(s)
}
}
func main(){
去说(“世界”)
说(“你好”)
}
来自:

程序执行首先初始化主包,然后调用函数
main
。当函数调用返回时,程序退出。它不会等待其他(非
main
)goroutine完成

因此,无法保证goroutine打印
“world”
在程序退出之前有时间完成

我怀疑,如果您运行该程序足够多的时间,您将在两个平台上看到9行和10行输出。将
GOMAXPROCS
环境变量设置为2也可能有助于触发问题

您可以通过使主goroutine显式地等待另一个goroutine的完成来修复它。例如,使用通道:

func say(s string, done chan<- bool) {
    for i := 0; i < 5; i++ {
        time.Sleep(1000 * time.Millisecond)
        fmt.Println(s)
    }
    done <- true
}

func main() {
    c := make(chan bool, 2)
    go say("world", c)
    say("hello", c)
    <-c
    <-c
}

func say(s string,done chant主函数在“world”goroutine第五次打印之前完成。这是一个竞赛条件。@inf,是的,我也从一个go合作者那里得到了很好的答案谢谢!