goroutine 是 Go 语言中一种轻量级的线程实现,其存在的意义是为了提高程序的并发能力和性能。相比于传统的线程实现,goroutine 的创建和销毁代价较小,且使用更加简便,可以通过 Go 语言提供的关键字 go 来启动一个 goroutine,示例如下:
package main
import (
"fmt"
"time"
)
func main() {
// 启动一个goroutine,执行printHello函数
go printHello()
// 主函数继续执行
fmt.Println("Main function continues to run...")
// 让主函数休眠一段时间,等待goroutine执行
time.Sleep(time.Second)
}
func printHello() {
fmt.Println("Hello from goroutine!")
}
在上述代码中,通过 go printHello() 启动了一个 goroutine 来执行 printHello 函数。由于 goroutine 的执行是异步的,因此主函数可以继续执行,而不需要等待 goroutine 执行完毕。在 printHello 函数中打印一条信息后,goroutine 就结束了。
goroutine 的另一个重要特性是可以通过 channel 来进行通信和同步,实现不同 goroutine 之间的数据传递和协作。例如:
package main
import (
"fmt"
"time"
)
func main() {
// 创建一个channel,用于传递数据
c := make(chan string)
// 启动一个goroutine,发送数据到channel
go sendHello(c)
// 从channel接收数据
msg := <-c
fmt.Println(msg)
}
func sendHello(c chan string) {
// 向channel发送数据
c <- "Hello from goroutine!"
}
在上述代码中,通过 make(chan string) 创建了一个字符串类型的 channel,然后启动了一个 goroutine,将字符串 “Hello from goroutine!” 发送到了该 channel 中。在主函数中,通过 <-c 从 channel 中接收数据,并打印出来。注意,在接收数据时,如果 channel 中没有数据,主函数会被阻塞,直到有数据可用为止。
这些例子展示了 goroutine 的基本用法和特性,通过 goroutine 可以方便地实现并发和并行的程序,提高程序的性能和效率。