Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@theckman
Last active April 17, 2018 15:43
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 theckman/283e6fde3ba6be0e9f6b965ca8f43623 to your computer and use it in GitHub Desktop.
Save theckman/283e6fde3ba6be0e9f6b965ca8f43623 to your computer and use it in GitHub Desktop.
func doWork(s string, ch <-chan struct{}, wg *sync.WaitGroup) {
defer func() {
<-ch // free up space in the semaphore
wg.Done() // tell the WaitGroup we're finished
}()
fmt.Println(s)
}
func execute(work []string) {
wg := &sync.WaitGroup{}
sema := make(chan struct{}, 10) // concurrency limit of 10
for _, url := range work {
// if there are 10 items in flight, channel is full / will block
// unblocks when a worker finishes
sema <- struct{}{}
wg.Add(1)
go doWork(url, sema)
}
// close the channel as nothing else should write
close(sema)
// wait for all goroutines to finish
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment