Golang 匿名Goroutines
为了能够理解 匿名goroutines ,我们必须意识到匿名函数和 goroutines 的存在 。 我们将首先探讨匿名函数,它是 匿名goroutines 动机背后的真正原因,然后我们将了解一下什么是 goroutines ,最后再检查几个 匿名goroutines 的例子。
匿名函数
在Golang中,匿名函数是那些没有任何名字的函数。简单地说,匿名函数在声明时不使用任何变量作为名称。
我们知道,我们用类似的语法声明一个函数,如下图所示。
func Sample(){
// some code
}
虽然我们对上述函数 (Sample) 有一个名字,但在匿名函数的情况下,我们并没有一个名字。
例子1
下面是一个非常简单的匿名函数的例子。
package main
import (
"fmt"
)
func main() {
func(name string) {
fmt.Println("Welcome to", name)
}("TutorialsPoint")
}
在上面的代码中,我们在 Go 程序的 主 函数里面有一个匿名函数。这个匿名函数需要一个参数,一旦该函数的代码块结束,该参数就被传递。
输出
如果我们运行这段代码,用命令 go run main.go ,我们会看到终端打印出以下输出。
Welcome to TutorialsPoint
Golang中的goroutines
goroutine 是一个极其轻量级的线程,由 Go 运行时管理。使用 goroutines ,我们可以编写异步的并行程序,可以比顺序程序更快地执行一些任务。
goroutines帮助我们使程序具有异步性,让我们在更短的时间内用更少的资源完成更多的工作。
所以, 匿名goroutine 背后的想法是,它只是一个匿名的函数,在一个单独的 goroutine 上运行,它是从这个 goroutine 上调用的。
例子2
让我们举一个非常基本的 匿名goroutine 的例子来更好地理解它。
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("before the anonymous goroutine")
go func(name string) {
fmt.Println("Welcome to", name)
}("TutorialsPoint")
time.Sleep(time.Second)
fmt.Println("after the anonymous goroutine")
}
在上面的例子中,我们使用了一个 匿名的goroutine ,为了确保主函数不会在 goroutine 完成工作之前完成,我们还写了一个 time.Sleep() 函数,它将把第二个 fmt.Println() 延迟1秒。
输出
如果我们在go run main.go命令的帮助下运行上述代码,那么我们将看到以下输出。
before the anonymous goroutine
Welcome to TutorialsPoint
after the anonymous goroutine
我们也可以不写 time.Sleep() 函数,而是使用任何可以阻断 主goroutine 的函数,这将给 主 函数中的 匿名goroutine 提供足够的时间来正常运行。
例三
考虑一下下面的代码。
package main
import (
"fmt"
)
func main() {
func(name string) {
fmt.Println("Welcome to", name)
}("TutorialsPoint")
fmt.Scanln() // blocking call
}
输出
如果我们在 go run main.go 命令的帮助下运行上述代码,那么我们将看到以下输出。
Welcome to TutorialsPoint
...