为什么有关golang goruntine运行顺序的代码为"2",为什么?第一的 [英] why this code about golang goruntine running order is "2" first

查看:77
本文介绍了为什么有关golang goruntine运行顺序的代码为"2",为什么?第一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

package main

import (
    "fmt"
    "sync"
)

func main() {
    runtime.GOMAXPROCS(1)
    w := &sync.WaitGroup{}
    w.Add(2)
    go func() {
        fmt.Println("1")
        w.Done()
    }()
    go func() {
        fmt.Println("2")
        w.Done()
    }()
    w.Wait()
}

https://play.golang.org/p/ESi1mKAo1x_S

嗯,我不知道为什么先打印"2".

eh,I don't know why the "2" is print first.

我想检查信息.但是我不知道应该检查什么信息,所以我在此处张贴问题以寻求帮助.

I want to check the information.But I don't know what's information should I check.So I post the question there for help.

我认为第一个goroutine是第一个推送队列.应该先打印.

I think the first goroutine is the first one push in queue。The it should be print first.

推荐答案

您没有将两个启动的goroutines 彼此同步,因此无法保证它们以什么顺序运行.您唯一要同步的是等待其他2个完成的主要goroutine,但是它们的顺序是不确定的.

You're not synchronizing your 2 launched goroutines to each other, so there is no guarantee in what order they run. The only thing you synchronize is the main goroutine to wait for the other 2 to complete, but their order will be undefined.

这是一个使用另一个sync.WaitGroup同步订单的示例:

Here's an example that also synchronizes order using another sync.WaitGroup:

w := &sync.WaitGroup{}
w.Add(2)

w2 := &sync.WaitGroup{}
w2.Add(1)
go func() {
    fmt.Println("1")
    w.Done()
    w2.Done()
}()
go func() {
    w2.Wait()
    fmt.Println("2")
    w.Done()
}()
w.Wait()

输出将是(在转到游乐场上尝试):

Output will be (try it on the Go Playground):

1
2

基本上,第二个goroutine等待w2,一旦完成,它就会在第一个goroutine中被调用.

Basically the 2nd goroutine waits for w2, which is called in the 1st goroutine once it's done.

请注意,由于第二个goroutine等待第一个goroutine,所以只需要等待第二个goroutine就足够了(传递式地等待第二个goroutine).因此,上面的示例可以这样写:

Note that since the 2nd goroutine waits for the first, it is enough for the main goroutine to only wait for the 2nd goroutine (which transitively means to wait for both). So the above example can be written like this:

w2 := &sync.WaitGroup{}
w2.Add(1)
go func() {
    fmt.Println("1")
    w2.Done()
}()

w := &sync.WaitGroup{}
w.Add(1)
go func() {
    w2.Wait()
    fmt.Println("2")
    w.Done()
}()
w.Wait()

输出是相同的.在去游乐场上尝试一下.

Output is the same. Try this one on the Go Playground.

这篇关于为什么有关golang goruntine运行顺序的代码为"2",为什么?第一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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