Reputation: 659
Th following codes is in The Go Programming Language
func mirroredQuery() string {
responses := make(chan string, 3)
go func() { responses <- request("asia.gopl.io") }()
go func() { responses <- request("europe.gopl.io") }()
go func() { responses <- request("americas.gopl.io") }()
return <-responses // return the quickest response
}
func request(hostname string) (response string) { /* ... */ }
And book says
Had we used an unbuffered channel, the two slower goroutines would have gotten stuck trying to send their responses on a channel from which no goroutine will ever receive . This situation, called a goroutine leak, would be a bug . Unlike garbage variables, leaked goroutines are not automatically collec ted, so it is important to make sure that goroutines terminate themselves when no longer needed.
And the question is why this situation will cause a goroutine
leak.In my idea, the buffered channel's cap
is 3, and 3 goroutines
will send their requests and exit immediately which will not cause the leak.
Upvotes: 1
Views: 1340
Reputation: 12393
The code shown does not cause a leak.
As the paragraph states:
Had we used an unbuffered channel
Meaning: if we had used an unbuffered channel...
So only if the channel was unbuffered the leak would occur.
Upvotes: 4