Goroutine 与主线程

1. 主 Goroutine

Go 程序启动时,主函数 main() 在主 Goroutine 中运行。

2. Goroutine 并发执行

通过 go 关键字启动新的 Goroutine,实现与主 Goroutine 并发执行。

func printMessage(msg string) {
    fmt.Println(msg)
}

func main() {
    go printMessage("Hello from Goroutine")
    fmt.Println("Hello from main Goroutine")
    time.Sleep(time.Second)  // 等待子 Goroutine 执行
}

`

3. 主 Goroutine 退出影响

主 Goroutine 退出时,程序终止,所有其他 Goroutine 也会停止执行。

4. 同步等待

常用 sync.WaitGroup 等工具确保所有 Goroutine 执行完成:

var wg sync.WaitGroup
wg.Add(1)

go func() {
    defer wg.Done()
    fmt.Println("Goroutine working")
}()

wg.Wait()
fmt.Println("All goroutines done")

理解 Goroutine 与主线程的关系,有助于正确编写并发程序。