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 程序的 main 函数中有一个匿名函数。这个匿名函数接受一个参数,并且该参数会在函数的代码块结束后立即传递。
输出
如果我们使用命令 go run main.go 运行此代码,我们将在终端中看到以下输出。
欢迎来到 TutorialsPoint
Golang 中的 goroutines
goroutine 是一个非常轻量级的线程,由 Go 运行时管理。使用 goroutines,我们可以编写异步并行程序,这些程序可以比顺序程序更快地执行某些任务。
Goroutines 帮助我们使程序本质上异步,让我们在更短的时间内用更少的资源完成更多工作。
因此,匿名 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 命令的帮助下运行上述代码,那么我们将看到以下输出。
匿名 goroutine 之前 欢迎来到 TutorialsPoint 匿名 goroutine 之后
除了编写time.Sleep()函数外,我们还可以使用任何可以阻止main goroutine 的函数,这将为匿名goroutine 在 main 函数内正常运行。
示例 3
考虑下面显示的代码。
package main import ( "fmt" ) func main() { func(name string) { fmt.Println("Welcome to", name) }("TutorialsPoint") fmt.Scanln() // 阻塞调用 }
输出
如果我们在 go run main.go 命令的帮助下运行上述代码,那么我们将看到以下输出。
Welcome to TutorialsPoint ...