并发编程是 Go 语言最强大的特性之一。Go 在语言层面提供了 Goroutine 和 Channel,让并发编程变得简单高效。本部分将系统讲解 Go 的并发模型和实践技巧。
Goroutine 是 Go 语言轻量级线程的实现。本章讲解:
Channel 是 Goroutine 之间通信的管道。本章涵盖:
Select 用于处理多个 Channel 操作。本章介绍:
并发同步用于协调多个 Goroutine 的执行。本章讲解:
Context 用于控制 Goroutine 的生命周期。本章涵盖:
Goroutine:
// 启动 Goroutine
go func() {
fmt.Println("Hello from goroutine")
}()
// 带 WaitGroup
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// 执行任务
}()
wg.Wait()
Channel:
// 创建 Channel
ch := make(chan int)
chBuffered := make(chan int, 10)
// 发送和接收
go func() {
ch <- 42 // 发送
}()
value := <-ch // 接收
// 关闭和遍历
close(ch)
for v := range ch {
fmt.Println(v)
}
Select:
select {
case v := <-ch1:
fmt.Println("ch1:", v)
case v := <-ch2:
fmt.Println("ch2:", v)
case <-time.After(time.Second):
fmt.Println("超时")
default:
fmt.Println("无数据")
}
Context:
// 创建带超时的 Context
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// 在 Goroutine 中使用
go func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("被取消")
}
}(ctx)