1

According to the GOPL, "A select waits until a communication for some case is ready to proceed", then what happens to the channel that is not selected? Further, will the goroutine which is sending a message to the "unselected" channel gets stuck and thus causing a goroutine leak?

Or because the "unselected" channel is unreachable, it is collected by the GC (immediately?) and the stuck goroutine is also collected?

1
  • Goroutines are not "collected" (terminate and have their resources freed up) until the function they are running completes its execution or panics and crashes the process. Remember that channel sending operations are also a valid select case, so you can attempt to send on a channel, but then timeout and do something else (e.g. terminate the goroutine) if the send does not succeed for a set amount of time. Dec 26, 2020 at 7:54

1 Answer 1

4

Unselected channels will be left "intact". More precisely the unselected communication operations will not be executed.

Whether this causes a deadlock or goroutine leak in your app is entirely up to your app. You may have multiple goroutines sending on / receiving from those channels, and the select may be in a loop executing the select repeatedly, ultimately executing all ready communication ops.

Channels–like all values in Go–are garbage collected when they become unreachable, that is, no Go code has a "reference" to them. If a goroutine is blocked trying to send on / receive from a channel, that counts as "having a reference" to the channel, and so the garbage collector cannot "salvage" that channel.

The garbage collector is not a tool to solve your deadlock situations but to free unreachable, unused memory. You have to think about solving deadlocks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.