Select With Default And Timeout

Use select with a default branch for non-blocking channel sends and receives, and a time.After branch to bound how long a receive waits.

GoResilience

Code

gosnippet
39 lines
package main

import (
	"fmt"
	"time"
)

func main() {
	queue := make(chan int, 2)
	const timeout = 50 * time.Millisecond

	// 非阻塞发送:缓冲满时 default 立即触发,而不是永久阻塞
	for i := 1; i <= 4; i++ {
		select {
		case queue <- i:
			fmt.Println("queued:", i)
		default:
			fmt.Println("queue full, dropped:", i)
		}
	}

	// 非阻塞接收:先取走积压元素,再空转一次展示 default
	for i := 0; i < 3; i++ {
		select {
		case v := <-queue:
			fmt.Println("drained:", v)
		default:
			fmt.Println("queue empty, nothing to receive")
		}
	}

	// 超时分支:select 挂起等待,超过 50ms 走 time.After
	select {
	case v := <-queue:
		fmt.Println("late item:", v)
	case <-time.After(timeout):
		fmt.Println("timeout: no item within 50ms")
	}
}

Walkthrough of the file

Select With Default And Timeout reduces to the function main.

Repetition is confined to for i := 1; i <= 4; i++ — the rest of the file is straight-line.

Applying it

The run emits 6 labeled sections — queued:, queue full, dropped:, drained:, queue empty, nothing to receive, late item:, timeout: no item within 50ms — one per step.

Statements that matter

queue := make(chan int, 2)

Interactive Tools for This Topic

FAQ

What does Select With Default And Timeout print when run?
Execute the whole file; each printed line is prefixed with a label like `queued:`, `queue full, dropped:`, `drained:`.