在下面的代码中:
package main
import (
"context"
"fmt"
"time"
)
func cancellation() {
duration := 150 * time.Millisecond
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
ch := make(chan string)
go func() {
time.Sleep(time.Duration(500) * time.Millisecond)
ch <- "paper"
}()
select {
case d := <-ch:
fmt.Println("work complete", d)
case <-ctx.Done():
fmt.Println("work cancelled")
}
time.Sleep(time.Second)
fmt.Println("--------------------------------------")
}
func main() {
cancellation()
}
由于无缓冲通道(
ch := make(chan string)
),由于发送受阻而导致常规泄漏(
ch <- "paper"
),如果主goroutine尚未准备好接收。
使用缓冲通道
ch := make(chan string, 1)
不阻止发送(
ch<-“纸”
)
如何检测此类常规泄漏?