Skip to content

Instantly share code, notes, and snippets.

@xcsrz
Created June 28, 2025 20:41
Show Gist options
  • Save xcsrz/606ce064906e3fc5ff4a237ed6077d3c to your computer and use it in GitHub Desktop.
Save xcsrz/606ce064906e3fc5ff4a237ed6077d3c to your computer and use it in GitHub Desktop.
The essential components of a golang "worker pool" using a semaphore channel to control the number of concurrent executions. This is just a basic example to demonstrate the concepts, values of combining (fixed size) queues and goroutines without adding complexity like generics or multiple pools.
package main
import (
"fmt"
"time"
)
const maxWorkers = 2
func processTask(task int) {
fmt.Printf("Processing task %d\n", task)
time.Sleep(time.Second)
fmt.Printf("Done task %d\n", task)
}
func runInWorkers(tasks []int) {
sem := make(chan struct{}, maxWorkers)
for _, task := range tasks {
sem <- struct{}{} // Acquire semaphore
go func(task int) {
defer func() { <-sem }() // Release semaphore
processTask(task)
}(task)
}
// Wait for all workers to finish
for i := 0; i < maxWorkers; i++ {
sem <- struct{}{}
}
}
func main() {
tasks := []int{1, 2, 3, 4, 5}
runInWorkers(tasks)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment