Skip to content

Instantly share code, notes, and snippets.

@ydm
Created August 6, 2024 08:32
Show Gist options
  • Save ydm/494e2730d22c9e93a1d4ed8885ee07c7 to your computer and use it in GitHub Desktop.
Save ydm/494e2730d22c9e93a1d4ed8885ee07c7 to your computer and use it in GitHub Desktop.
A clever way to limit the number of goroutine workers.
package main
import (
"context"
"fmt"
"sync"
"time"
)
func f(ctx context.Context, xs []int) {
var wg sync.WaitGroup
maxGoroutines := 3
guard := make(chan struct{}, maxGoroutines)
for _, x := range xs {
guard <- struct{}{} // Acquire a slot.
wg.Add(1)
go func(x int) {
defer wg.Done()
defer func() { <-guard }() // Release the slot.
select {
case <-ctx.Done():
return
default:
fmt.Printf("[X] Sleeping: x=%d\n", x)
time.Sleep(3 * time.Second)
}
}(x)
}
wg.Wait()
}
func main() {
f(context.Background(), []int{0, 1, 2, 3, 4, 5, 6, 7})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment