Last active
April 17, 2018 15:43
-
-
Save theckman/283e6fde3ba6be0e9f6b965ca8f43623 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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