Skip to content

Instantly share code, notes, and snippets.

@jkomyno
Created October 22, 2018 09:27
Show Gist options
  • Save jkomyno/c268d86f029aa24d4e79aedce95b6af3 to your computer and use it in GitHub Desktop.
Save jkomyno/c268d86f029aa24d4e79aedce95b6af3 to your computer and use it in GitHub Desktop.
// parallel processes the data in separate goroutines.
func parallel(start, stop int, fn func(<-chan int)) {
count := stop - start
if count < 1 {
return
}
procs := runtime.GOMAXPROCS(0)
if procs > count {
procs = count
}
c := make(chan int, count)
for i := start; i < stop; i++ {
c <- i
}
close(c)
var wg sync.WaitGroup
for i := 0; i < procs; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fn(c)
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment