Skip to content

Instantly share code, notes, and snippets.

@tristanfisher
Created November 17, 2020 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tristanfisher/58b7145ec0625404a1121d00c5cd0808 to your computer and use it in GitHub Desktop.
Save tristanfisher/58b7145ec0625404a1121d00c5cd0808 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
)
func simulatedWork(id int) {
time.Sleep(250 * time.Millisecond)
fmt.Printf("work id: %d at %s\n", id, time.Now().Format(time.StampMilli))
}
func boundedParallelism(maxParallelCalls int, workQueue []int) {
// wg so we don't return until everything is done
var wg sync.WaitGroup
// struct{} is the smallest data type in go (no allocation necessary)
guard := make(chan struct{}, maxParallelCalls)
workQueueLen := len(workQueue)
for i := 0; i < workQueueLen; i++ {
guard <- struct{}{} // blocks if the channel full
wg.Add(1)
go func(workId int) {
simulatedWork(workId)
wg.Done()
<-guard // read from the channel and discard -- make another call
}(i)
}
wg.Wait()
}
func main() {
maxParallelCalls := 10
fakeNumRecords := 25
// this is just test setup
var fakeWorkQueue []int
for i := 0; i < fakeNumRecords; i++ {
fakeWorkQueue = append(fakeWorkQueue, i)
}
// pretend this is sql exec or some other void call
boundedParallelism(maxParallelCalls, fakeWorkQueue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment