什么决定了 goroutine 的执行顺序?

And*_*ang 1 concurrency go goroutine

我有这个基本的 go 程序,它打印到控制台并调用 2 个 goroutines

package main

import (
    "fmt"
    "time"
)

func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}

func main() {
    f("hello")
    go f("foo")
    go f("bar")
    time.Sleep(time.Second)
}
Run Code Online (Sandbox Code Playgroud)

输出如下——我想知道为什么在“foo”之前打印“bar”——是什么决定了 goroutines 的执行顺序?

hello : 0
hello : 1
hello : 2
bar : 0
bar : 1
bar : 2
foo : 0
foo : 1
foo : 2
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 6

你有独立的、并发的 goroutines。没有指定执行顺序,任何不违反Go Memory Model 的顺序都是有效的。

如果您需要特定的顺序,只有显式同步才能保证(例如互斥锁、锁、通信操作等)。

相关问题:

golang中不正确的同步

Golang 需要锁定才能读取 int

Go Playground 和 Go 在我的机器上的差异?

如何在 goroutine 闭包中更改外部变量的值