Go 并发编程
Go 的并发模型基于 CSP(Communicating Sequential Processes)理论。
Goroutine
Goroutine 是 Go 的轻量级线程。
go
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
Channel 用于 goroutine 间通信。
go
// 创建 channel
ch := make(chan int)
// 发送数据
go func() {
ch <- 42
}()
// 接收数据
value := <-ch
fmt.Println(value)
带缓冲的 Channel
go
ch := make(chan int, 2) // 缓冲区大小为 2
ch <- 1
ch <- 2
// ch <- 3 // 会阻塞,因为缓冲区已满
fmt.Println(<-ch) // 输出: 1
fmt.Println(<-ch) // 输出: 2
Select 语句
go
select {
case msg := <-ch1:
fmt.Println("收到 ch1:", msg)
case msg := <-ch2:
fmt.Println("收到 ch2:", msg)
case <-time.After(time.Second):
fmt.Println("超时")
}
WaitGroup
同步等待多个 goroutine 完成。
go
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Printf("Worker %d 完成\n", id)
}(i)
}
wg.Wait() // 等待所有 goroutine 完成