简介

Go 的并发模型是其核心特性之一。本文介绍 goroutine 和 channel 的基础用法。

Goroutine 基础

package main

import (
    "fmt"
    "time"
)

func sayHello() {
    fmt.Println("Hello from goroutine!")
}

func main() {
    go sayHello() // 启动一个 goroutine

    time.Sleep(time.Second) // 等待 goroutine 执行
    fmt.Println("Main function")
}

Channel 通信

package main

import "fmt"

func main() {
    ch := make(chan string)

    go func() {
        ch <- "Message from goroutine"
    }()

    msg := <-ch
    fmt.Println(msg)
}

总结

Go 的并发模型简洁而强大,通过 goroutine 和 channel 可以轻松实现高并发程序。