goroutine#
func main() {
go func() {
fmt.Println("后台执行")
}()
fmt.Println("主流程")
// 主流程结束,程序就退出
}goroutine 是 Go 的轻量级协程。初始栈只有 2KB(可增长到 1GB),创建成本比线程低几个数量级,一个进程可以有几十万个 goroutine。
等待 goroutine 结束#
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
fmt.Println(i)
}(i)
}
wg.Wait()注意 go func(i int) 的参数传递——这是 Go 1.22 之前的必要写法(1.22 之后循环变量每轮独立,但仍建议显式传参,代码更清晰且兼容旧版本)。
WaitGroup 的坑#
defer wg.Done() // ✅
wg.Done() // ❌ 忘记调用会死锁永远用 defer wg.Done(),且 wg.Add(1) 要在 go 之前。
channel#
ch := make(chan int) // 无缓冲
ch := make(chan int, 10) // 有缓冲,容量 10
ch := make(chan int, 0) // 等价于无缓冲发送与接收#
ch <- 42 // 发送
v := <-ch // 接收
v, ok := <-ch // ok 为 false 表示 channel 已关闭且已排空关闭#
close(ch)关闭后:
- 接收端立即返回零值,
ok为 false - 向已关闭的 channel 发送会 panic
- 重复关闭会 panic
- 只有发送方应该关闭 channel
什么时候需要缓冲#
缓冲 channel 是「削峰」的工具:
ch := make(chan Task, 100)
go worker(ch) // 单个消费者无缓冲 channel 是「同步点」,发送方和接收方必须会合。选哪个取决于你想不想让生产者被消费者拖住。
// 同步:必须等消费者处理完
ch := make(chan Task)
go func() {
for t := range ch {
process(t)
}
}()
ch <- task // 阻塞直到消费者接手
close(ch)range 遍历#
for v := range ch {
fmt.Println(v)
}
// channel 关闭后自动结束这是最常用的消费模式。
select#
select 让一个 goroutine 同时等待多个 channel 操作:
select {
case v := <-ch1:
fmt.Println("ch1:", v)
case v := <-ch2:
fmt.Println("ch2:", v)
case ch3 <- v:
fmt.Println("发送到 ch3")
case <-time.After(time.Second):
fmt.Println("超时")
}规则:
- 没有 case 就绪时阻塞
- 有多个 case 就绪时随机选一个(保证公平)
- 带
default则不阻塞,直接走 default
超时的标准写法#
select {
case res := <-ch:
return res
case <-time.After(5 * time.Second):
return ErrTimeout
}time.After 会泄漏 timer 直到它触发,热路径上用 time.NewTimer 并记得 Stop():
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
select {
case res := <-ch:
return res
case <-timer.C:
return ErrTimeout
}空转检测#
select {
case v := <-ch:
handle(v)
default:
// 队列空了,做点别的
}注意:带 default 的 select 是非阻塞的,在高并发场景可能造成 CPU 空转。生产代码里慎用。
context:取消与超时#
context.Context 是 Go 标准的取消机制,函数应该把 ctx 作为第一个参数传下去。
func Handle(ctx context.Context, req *Request) (*Response, error) {
// 检查是否已取消
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
// ...
}派生 context#
ctx, cancel := context.WithCancel(parent)
defer cancel() // 必须调用,否则泄漏
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()
ctx, cancel := context.WithValue(parent, key, val)
defer cancel()传播取消#
func fetch(ctx context.Context) error {
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("请求 %s: %w", url, err)
}
defer resp.Body.Close()
// ...
}调用方取消后,HTTP 请求会被中断。
context 的值:慎用#
context.WithValue 用于跨 API 边界传递请求作用域的数据(如 trace ID、认证信息),不要用来传可选参数。
type ctxKey struct{}
ctx = context.WithValue(ctx, ctxKey{}, traceID)key 必须是未导出的自定义类型,否则会和其他包冲突。
goroutine 泄漏#
goroutine 泄漏是最隐蔽的问题:goroutine 卡在 channel 收发或锁上,永远不退出,但也不报错。
常见原因:
- 往一个无人接收的 channel 发送
- 从一个永不关闭的 channel 接收
- 等待一个永远不会完成的
<-ctx.Done()(ctx 没 cancel) - 持有 mutex 时阻塞
排查泄漏#
func TestNoGoroutineLeak(t *testing.T) {
before := runtime.NumGoroutine()
// ... 执行被测代码 ...
// 等待 goroutine 退出
time.Sleep(100 * time.Millisecond)
after := runtime.NumGoroutine()
if after > before {
t.Errorf("goroutine 泄漏: before=%d after=%d", before, after)
}
}go.uber.org/goleak 是更专业的工具,能给出泄漏栈。
Go 1.26/1.27:内置的 goroutine 泄漏剖析#
Go 1.26 引入了实验性的 goroutine 泄漏 profile(GOEXPERIMENT=goroutineleakprofile),Go 1.27 正式可用。
# Go 1.27+:直接用
curl -o leak.out http://localhost:6060/debug/pprof/goroutineleak
go tool pprof -top leak.out它的判定逻辑很聪明:借助 GC 的可达性分析。
如果 goroutine G 阻塞在某个并发原语 P(channel、
sync.Mutex、sync.Cond等)上, 而 P 从任何可运行的 goroutine、或那些 goroutine 能唤醒的对象都不可达, 那么 P 永远不可能被解锁,G 就永远醒不过来。
这能覆盖一大类「永久阻塞」型泄漏,而且不采样时零运行时开销(由 GC 顺带完成),可以放心开在生产环境。
因为依赖可达性分析,如果阻塞的并发原语通过全局变量或可运行 goroutine 的局部变量可达,运行时可能识别不出泄漏。 所以 profile 是利器,但不是银弹——go.uber.org/goleak 那种「测试结束断言 goroutine 数量」的做法仍然值得保留。
避免泄漏的结构#
func producer(ctx context.Context) <-chan int {
ch := make(chan int)
go func() {
defer close(ch) // 发送方关闭
for {
select {
case <-ctx.Done():
return // 取消时退出
case ch <- 1:
}
}
}()
return ch
}发送方要同时监听 ctx.Done(),否则消费者不再消费时会永久阻塞。
数据竞争#
Go 内置的 map、切片、普通变量都不是并发安全的。
go func() { m["a"] = 1 }() // 写
go func() { _ = m["a"] }() // 读会触发 fatal error: concurrent map writes——这个错误无法 recover,直接终止进程。
普通变量的数据竞争不会 panic,但结果不可预测。必须用 -race 检测:
go test -race ./...
go run -race main.go-race 应该出现在 CI 里。
用 channel 传递数据#
Go 官方原则:Do not communicate by sharing memory; instead, share memory by communicating.
// 不好:共享变量
var counter int
go func() { for i := 0; i < 1000; i++ { counter++ } }()
go func() { for i := 0; i < 1000; i++ { counter++ } }()
// 好:用 channel 传递
ch := make(chan int)
done := make(chan bool)
go func() {
for v := range ch {
counter += v
}
done <- true
}()
for i := 0; i < 1000; i++ {
ch <- i
}
close(ch)
<-done但 channel 有开销。如果只是保护一个简单计数器,用 sync/atomic 更合适:
var counter int64
atomic.AddInt64(&counter, 1)管道模式#
func gen(nums ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums {
out <- n
}
}()
return out
}
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in {
out <- n * n
}
}()
return out
}
func sum(in <-chan int) int {
total := 0
for n := range in {
total += n
}
return total
}
// 使用
result := sum(square(gen(1, 2, 3))) // 14方向很重要:函数返回 <-chan int(只读)而不是 chan int,这样调用方无法往里写,管线更安全。
常见反模式#
1. 在 goroutine 里用带缓冲 channel 但永不消费#
ch := make(chan int, 100)
go func() {
for i := 0; i < 1000; i++ {
ch <- i // 塞满 100 后永久阻塞
}
}()2. 忘记 close#
ch := make(chan int)
go func() { ch <- 1 }()
// 接收方 for range ch 会永久阻塞3. 重复 close#
close(ch)
close(ch) // panic: close of closed channel4. 向 nil channel 发送#
var ch chan int
ch <- 1 // 永久阻塞(nil channel 的收发永远阻塞)nil channel 在 select 里是「禁用这个 case」的有用技巧:
var ch chan int // nil
select {
case v := <-ch: // 这个 case 永远不会触发
fmt.Println(v)
case <-ctx.Done():
fmt.Println("退出")
}小结#
- goroutine 轻量但不是免费,用 WaitGroup 等它们结束
- channel 由发送方关闭,接收方用
ok或range判断 select随机选择就绪的 case,time.After在热路径要换成Timer- 所有需要取消的函数第一个参数是
ctx,派生出来的 ctx 一定要defer cancel() - 用
-race检测数据竞争,写进 CI - goroutine 泄漏靠
runtime.NumGoroutine()或 goleak 检测