Do goroutines collect garbage along with their channels?

Provide the following code:

func waitForOneOfTwoProcesses() { c := make(chan bool) go func() { time.Sleep(1 * time.Second) c<-true }() go func() { time.Sleep(2 * time.Second) c<-true }() <-c } 

Is it a channel leak and goroutine or does Go recognize that c gone and can goroutine exit?

Will the answer be different if the channel has a buffer size of 2?

+5
source share
1 answer

If the channel is unbuffered, then one of the anonymous functions will not return. Goroutine and channel leak program.

If the channel has a buffer size greater than or equal to one, then both anonymous functions are returned. The resources used by the larynx and canals will be restored.

A single buffer size is sufficient to prevent leakage. The waitForOneOfTwoProcesses function gets one of the values ​​sent to c . The second value sent to c is buffered in the channel (which is collected by the GC).

Another way to ensure goroutines return is to use non-blocking submission. Replace the lines c <- true with:

  select { case c <- true: default: } 
+3
source

All Articles