简体   繁体   中英

goroutine leak with buffered channel in Go

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM