Wednesday, January 14, 2026

goroutine - Semaphore Pattern with sync.Semaphore (Go 1.19+)

 package main


import (

"fmt"

"sync"

"sync/atomic"

"time"

)


func task(id int, sem *sync.Semaphore, totalTasks *int32, wg *sync.WaitGroup) {

defer wg.Done()

defer sem.Release(1) // Release the semaphore when done

// Simulate task execution

time.Sleep(time.Millisecond * time.Duration(100+id*10))

atomic.AddInt32(totalTasks, 1)

fmt.Printf("Task %d completed\n", id)

}


func main() {

const numTasks = 50

const maxConcurrency = 10

var wg sync.WaitGroup

var totalTasks int32

sem := sync.NewSemaphore(maxConcurrency)

for i := 1; i <= numTasks; i++ {

wg.Add(1)

sem.Acquire(1) // Wait for available slot

go task(i, sem, &totalTasks, &wg)

}

wg.Wait()

fmt.Printf("\nSummary: %d tasks completed with max %d concurrent workers\n", 

atomic.LoadInt32(&totalTasks), maxConcurrency)

}

No comments:

Post a Comment