Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I explicitly empty a channel?

Tags:

go

channels

The short version: Is there a way to empty a go channel without recreating it, or looping through it?

The why: I'm using two channels to send and receive data, and I have an extra channel to signal that a reconnect is needed.

Now when the transport has been reset/reconnected I want to 'empty' the extra channel to make sure that there is not any lingering other reset requests which would cause the thing to reconnect again.

like image 270
Toad Avatar asked Oct 01 '14 13:10

Toad


People also ask

What happens when you close a channel in Go?

Closing a channel indicates that no more values will be sent on it. This can be useful to communicate completion to the channel's receivers. In this example we'll use a jobs channel to communicate work to be done from the main() goroutine to a worker goroutine.

How do I gracefully close a channel?

The Channel Closing Principle One general principle of using Go channels is don't close a channel from the receiver side and don't close a channel if the channel has multiple concurrent senders. In other words, we should only close a channel in a sender goroutine if the sender is the only sender of the channel.

Do you need to close channels?

You needn't close every channel when you've finished with it. It's only necessary to close a channel when it is important to tell the receiving goroutines that all data have been sent.

How do you close a Goroutine?

Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.


Video Answer


1 Answers

It is not possible to empty a channel without a loop. If you don't have any concurrent receivers, then you can use this simple loop:

for len(ch) > 0 {
  <-ch
}

If you do have concurrent receivers, then use the loop:

L:
for {
    select {
    case <-c:
    default:
       break L
    }
}
like image 121
Simon Fox Avatar answered Sep 18 '22 14:09

Simon Fox