How to implement non-blocking write to an unbuffered channel?

You can always avoid blocking while (probably) still guaranteeing delivery by using another goroutine:

go func() { channel <- message }()

Of course, this is just using the goroutine scheduler as a substitute buffer for your channel, which may or may not be wise.


What it means when it says os.Notify will not block is the messages will be dropped were it to block. So while it's true that it doesn't block, it's not true that it will relay the signals if they can't be received immediately. This is done via simple select:

select {
    case channel <- message:
        // message sent
    default:
        // message dropped
}

Which is why the documentation for Notify explicitly states that you should use a buffered channel. Also note that buffered channels can also block, not just unbuffered channels; buffered channels only block if the buffer is already full.

select is covered in the tour and the spec.

Tags:

Channel

Go