Select On Done To Cancel A Receive

Race a slow channel receive against a closed done channel so a cancelled waiter exits immediately instead of blocking forever.

GoResilience

Code

snippet
package main

import (
	"fmt"
	"time"
)

func main() {
	slow := make(chan string) // 没有人往里发送
	done := make(chan struct{})

	go func() {
		time.Sleep(20 * time.Millisecond)
		close(done) // 关闭即广播:所有等待者同时被唤醒
	}()

	select {
	case v := <-slow:
		fmt.Println("received:", v)
	case <-done:
		fmt.Println("cancelled before any value arrived")
	}

	// 关闭后的 done 再次接收也不再阻塞,ok 为 false
	_, ok := <-done
	fmt.Println("done still open:", ok)
}

How it works

Select On Done To Cancel A Receive reduces to the function main.

Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts.

Caveats

  • Self-contained — no imports beyond what the runtime already provides.

Using it

Signature: func main()

The demo output is labeled (received:, cancelled before any value arrived, done still open:); each label names the call that printed it.

Key statements

done := make(chan struct{})
slow := make(chan string) // 没有人往里发送
_, ok := <-done

Interactive Tools for This Topic

FAQ

What does Select On Done To Cancel A Receive print when run?
Running the file directly is enough — expect labeled output lines such as `received:`, `cancelled before any value arrived`, `done still open:`.