第一个例程,怪异的结果 [英] First goroutine example, weird results

查看:115
本文介绍了第一个例程,怪异的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此示例来自 tour.golang.org/#63

 包裹主要

进口(
fmt
时间


func say(s string){
for i:= 0;我< 5; i ++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}

func main(){
go say(world)
say(hello)
}



输出



  hello 
全球
hello
全球
hello
world
hello
world
hello

为什么世界仅打印 4 次而不是 5




编辑:答案可以从 golang规范
$ b


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



解决方案

<当你的主函数结束你的程序结束时,即所有的goroutines被终止。
您的主要终止在 go say(world)完成之前。如果你在主体的末端睡眠一段时间,你应该会看到最后的世界。


This example taken from tour.golang.org/#63

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}

The output

hello
world
hello
world
hello
world
hello
world
hello

Why world is printed only 4 times instead of 5 ?


Edit: The answer can be quoted from golang specification:

Program execution begins by initializing the main package and then invoking the function main. When the function main returns, the program exits. It does not wait for other (non-main) goroutines to complete.

解决方案

When your main function ends your program ends, i.e. all goroutines are terminated. Your main terminates before go say("world") is done. If you sleep some time at the end of main you should see the last world.

这篇关于第一个例程,怪异的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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