Buffered Channel Caps Concurrent Workers

Use a buffered chan struct{} as a counting semaphore: capacity caps concurrent workers, sends acquire, receives release, peak stays inside.

GoResilience

Code

gosnippet
40 lines
package main

import (
	"fmt"
	"sync"
)

func main() {
	// 缓冲通道当计数信号量:容量即并发上限,发送=获取,接收=释放
	sem := make(chan struct{}, 3)

	var mu sync.Mutex
	active, peak := 0, 0

	var wg sync.WaitGroup
	for i := 0; i < 8; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			sem <- struct{}{} // 获取:槽满则阻塞,直到有工人释放
			mu.Lock()
			active++
			if active > peak {
				peak = active
			}
			mu.Unlock()

			// 临界区:同一时刻最多 3 个工人到达这里
			mu.Lock()
			active--
			mu.Unlock()
			<-sem // 释放
		}()
	}
	wg.Wait()

	fmt.Println("peak stayed within cap:", peak <= 3)
	fmt.Println("all released:", active == 0)
}

What the code does

Buffered Channel Caps Concurrent Workers reduces to the function main.

Repetition is confined to for i := 0; i < 8; i++ — the rest of the file is straight-line. The goroutine/channel pair splits producer and consumer while keeping the handoff race-free. The cleanup call is deferred to function exit — success, early return, and panic all covered.

Points of care

  • The whole dependency story is the language version itself.

Using it

Output lines are prefixed (peak stayed within cap:, all released:), so the printed lines stay attributable to their steps.

Key statements

sem <- struct{}{} // 获取:槽满则阻塞,直到有工人释放
sem := make(chan struct{}, 3)
var wg sync.WaitGroup

Interactive Tools for This Topic

FAQ

What does Buffered Channel Caps Concurrent Workers print when run?
No setup needed: run the file and look for labeled lines like `peak stayed within cap:`, `all released:` in the output.