我想要做的是:,我正在尝试理解/构建一个包含三个阶段的go管道。第一阶段写入A频道,第二阶段有多个围棋例程。每个go例程从通道A读取,执行一些操作并将结果写入Channel Bn(Channel B1,B2..Bn)。第三阶段创建了n(=第2阶段的通道总数) go例程,每个go例程从第2阶段从一个通道读取。
问题:管道工作正常,操作分布在go例程中。但是当我做了一个转义分析,发现从一个阶段发送到另一个阶段的通道参数被报告为“泄漏参数”。
代码片段:为了简单起见,我发布了显示第1阶段信道创建的代码,以及打印从stage通道1读取的值的第2阶段。
package main
import "fmt"
func createStageOne(numOfJobs int) <-chan int {
stageOneChannel := make(chan int)
go func(nJobs int) {
for i := 0; i < nJobs; i++ {
stageOneChannel <- i
}
close(stageOneChannel)
}(numOfJobs)
return stageOneChannel
} // stageOneChannel closes and go routine exits once nJobs are completed
func createStageTwo(in <-chan int, completionFlag chan struct{}) {
go func() {
for n := range in {
fmt.Println("Received from stage 1 channel ", n)
}
completionFlag <- struct{}{}
}()
}// Comes out of for loop when stage 1 channel closes and go routine also exits
func main() {
numOfJobs := 10
stageOneChannel := createStageOne(numOfJobs)
done := make(chan struct{})
createStageTwo(stageOneChannel, done)
<-done
}这是逃逸分析结果。
$ go build -gcflags "-m -l"
# concurrentHTTP/stackoverflow
./pipeline.go:7:5: func literal escapes to heap
./pipeline.go:7:5: func literal escapes to heap
./pipeline.go:6:25: make(chan int) escapes to heap
./pipeline.go:17:5: func literal escapes to heap
./pipeline.go:17:5: func literal escapes to heap
./pipeline.go:16:21: leaking param: in
./pipeline.go:16:36: leaking param: completionFlag
./pipeline.go:19:16: "Received from stage 1 channel " escapes to heap
./pipeline.go:19:16: n escapes to heap
./pipeline.go:19:15: createStageTwo.func1 ... argument does not escape
./pipeline.go:29:14: make(chan struct {}) escapes to heap为什么逃逸分析报告在completionFlag标志和标志中的上有泄漏?
发布于 2019-02-11 03:40:55
所讨论的参数是作为参考类型的通道。它们是在createStageTwo()中创建的闭包中捕获的,当createStageTwo()返回时,可以继续在该闭包的go例程中使用。因此,它们被视为泄漏参数。如果没有,则会将它们放在堆栈上,并在main()完成时失效。
这并不意味着你有问题。逃逸分析并不是用来检测资源泄漏的,而且大多数人都不需要使用它。(如果在GC堆上放置了一些您不希望看到的东西,则可能对性能问题很有用。)
(对不起,@Volker,我最初在评论中发布了我的答案,这让你的问题悬而未决。)
https://stackoverflow.com/questions/54623302
复制相似问题