Semaphore

Limit concurrency with a buffered channel as a semaphore.

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	sem := make(chan struct{}, 3) // max 3 concurrent
	var wg sync.WaitGroup

	for i := 1; i <= 10; i++ {
		wg.Add(1)
		sem <- struct{}{} // acquire slot

		go func(id int) {
			defer wg.Done()
			defer func() { <-sem }() // release slot

			fmt.Printf("task %d started at %s\n", id, time.Now().Format("15:04:05.000"))
			time.Sleep(500 * time.Millisecond) // simulate work
			fmt.Printf("task %d done\n", id)
		}(i)
	}

	wg.Wait()
	fmt.Println("all tasks complete")
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy