Concurrency

Semaphore

Controls access to resources by multiple goroutines.

Connection limitingRate limitingResource pooling

Understanding Semaphore

A Semaphore limits concurrent access to a resource. In Go, it's typically implemented using a buffered channel where the buffer size represents available slots.

How It Works

Goroutines
G1
G2
G3
G4
G5
Semaphore (max: 3)
0/3 slots used
Resource
💤 Idle
5 goroutines want access
1

Goroutines Waiting

Multiple goroutines want to access a limited resource.

1 / 4

Basic Implementation

Simple semaphore with acquire/release:

main.go
Loading editor...

Real-World Example: Rate Limiter

API rate limiting with semaphore:

main.go
Loading editor...