【问题标题】:What determines the order of execution of goroutines?什么决定了 goroutine 的执行顺序?
【发布时间】:2020-10-03 23:05:06
【问题描述】:

我有这个基本的 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)
}

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

hello : 0
hello : 1
hello : 2
bar : 0
bar : 1
bar : 2
foo : 0
foo : 1
foo : 2

【问题讨论】:

    标签: go concurrency goroutine


    【解决方案1】:

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

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

    相关问题:

    Incorrect synchronization in go lang

    Golang needs lock to read an int

    Discrepancies between Go Playground and Go on my machine?

    How to change external variable's value inside a goroutine closure

    【讨论】:

      【解决方案2】:

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

      什么都没有。 Goroutines 执行顺序未确定。

      【讨论】:

      • 鉴于计算机操作是确定性的......怎么可能绝对没有明显的原因可能导致一个 goroutine 在另一个之前执行?是完全随机的吗?
      • @AndrewTang: Are computer operations deterministic? 我们倾向于希望它们存在,并认为它是一个错误或(如维基百科页面所说)“小故障”,而实际上它们不是。但即使它们适用于大多数情况,它们是否过于复杂而无法预测?它们可能取决于外部事件的发生时间吗? (他们可能会。)
      • @AndrewTang 当然,有个原因,但没有人知道和依赖。每个编译器、每个编译器版本、每个硬件甚至星期六的原因都可能不同。简而言之:这里没有什么可知道的。
      猜你喜欢
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2011-10-25
      • 1970-01-01
      • 2023-03-13
      • 2011-03-16
      相关资源
      最近更新 更多