Goroutine 概念:直接调用 vs 使用函数字面量调用
Goroutine concept: direct call vs call using function literal
以下两个代码之间的基本区别是什么?不知何故,在第二个示例中 demo_process2()
从未被调用,但在第一个示例中它工作正常。
1.
go func() {
Must(demo_process1())
}()
demo_process2()
2.
go Must(demo_process1())
demo_process2()
其中 Must()
:
func Must(err error) {
if err != nil {
panic(err)
}
}
The function value and parameters are evaluated as usual in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. Instead, the function begins executing independently in a new goroutine.
在您的第一个示例中,您启动了一个没有参数的匿名函数(函数文字)作为一个新的 goroutine。 Must()
和 demo_process1()
在其中被调用, 同时 与 demo_process2()
(在 "original" goroutine 中执行)。
然而在你的第二个例子中:
go Must(demo_process1())
demo_process2()
作为 goroutine 启动的函数是 Must()
,其参数在调用 goroutine 中计算 。 Must()
的参数是 demo_process1()
的 return 值,这意味着 demo_process1()
在启动新的 goroutine 之前先被调用并等待。只有当它 return 时,新的 goroutine 才能启动并调用 demo_process2()
(在 "original" goroutine 上)。
总而言之,在第二个示例中,demo_process1()
和 demo_process2()
不是同时 运行,而是在同一个 goroutine 中顺序执行。只有 Must()
在新的 goroutine 上执行(与 demo_process2()
同时执行)。
以下两个代码之间的基本区别是什么?不知何故,在第二个示例中 demo_process2()
从未被调用,但在第一个示例中它工作正常。
-
1.
go func() {
Must(demo_process1())
}()
demo_process2()
-
2.
go Must(demo_process1())
demo_process2()
其中 Must()
:
func Must(err error) {
if err != nil {
panic(err)
}
}
The function value and parameters are evaluated as usual in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. Instead, the function begins executing independently in a new goroutine.
在您的第一个示例中,您启动了一个没有参数的匿名函数(函数文字)作为一个新的 goroutine。 Must()
和 demo_process1()
在其中被调用, 同时 与 demo_process2()
(在 "original" goroutine 中执行)。
然而在你的第二个例子中:
go Must(demo_process1())
demo_process2()
作为 goroutine 启动的函数是 Must()
,其参数在调用 goroutine 中计算 。 Must()
的参数是 demo_process1()
的 return 值,这意味着 demo_process1()
在启动新的 goroutine 之前先被调用并等待。只有当它 return 时,新的 goroutine 才能启动并调用 demo_process2()
(在 "original" goroutine 上)。
总而言之,在第二个示例中,demo_process1()
和 demo_process2()
不是同时 运行,而是在同一个 goroutine 中顺序执行。只有 Must()
在新的 goroutine 上执行(与 demo_process2()
同时执行)。