Skip to content

Instantly share code, notes, and snippets.

@yumed15
Created November 28, 2023 10:15
Show Gist options
  • Save yumed15/66751b9c1bb3426b035c7b1e57082cc5 to your computer and use it in GitHub Desktop.
Save yumed15/66751b9c1bb3426b035c7b1e57082cc5 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
const concurrencyLimit = 2
requests := []string{"Request 1", "Request 2", "Request 3", "Request 4", "Request 5"}
var wg sync.WaitGroup
ch := make(chan string, concurrencyLimit)
for _, req := range requests {
wg.Add(1)
go func(r string) {
defer wg.Done()
ch <- r // Send request into the channel
processRequest(r)
<-ch // Receive from the channel to make room for the next request
}(req)
}
wg.Wait()
close(ch)
}
func processRequest(request string) {
// Simulate processing time
time.Sleep(2 * time.Second)
fmt.Printf("Processed: %s\n", request)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment