Unbuffered Channels Hand Off In Lockstep

Show an unbuffered channel blocking the sender until the receiver is ready, while a buffered channel absorbs sends up to capacity without anyone waiting.

GoData Integrity

Code

gosnippet
33 lines
package main

import "fmt"

func main() {
	// 无缓冲通道:发送阻塞到接收方就绪,每次传递都是一次会合
	ch := make(chan int)
	acked := make(chan struct{})

	go func() {
		for v := 1; v <= 3; v++ {
			fmt.Println("sender: ready with", v)
			ch <- v // 阻塞,直到 main 执行接收
			<-acked // 等接收方打印完,输出顺序才可读
		}
		close(ch)
	}()

	for v := range ch {
		fmt.Println("receiver: took", v)
		acked <- struct{}{}
	}

	// 缓冲通道对比:容量内的发送不需要接收者在场
	buffered := make(chan int, 2)
	buffered <- 1
	buffered <- 2
	fmt.Println("buffered absorbs:", len(buffered), "of cap", cap(buffered))

	// close 之后再次接收立即得到零值,不会阻塞
	last, ok := <-ch
	fmt.Println("after close:", last, ok)
}

How the snippet works

Unbuffered Channels Hand Off In Lockstep reduces to the function main.

Repetition is confined to for v := 1; v <= 3; v++ — the rest of the file is straight-line. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts.

Using it

The demo output is labeled (sender: ready with, receiver: took, buffered absorbs:), so each line traces straight back to the statement that printed it.

Key statements

acked := make(chan struct{})
for v := range ch {
	fmt.Println("receiver: took", v)
	acked <- struct{}{}
}
buffered := make(chan int, 2)

Interactive Tools for This Topic

FAQ

What does Unbuffered Channels Hand Off In Lockstep print when run?
Execute the whole file; each printed line is prefixed with a label like `sender: ready with`, `receiver: took`, `buffered absorbs:`.