Skip to content

Instantly share code, notes, and snippets.

@s0md3v
Last active October 15, 2020 08:52
Show Gist options
  • Save s0md3v/78ca77b8bfc16649eaa81762039d62c7 to your computer and use it in GitHub Desktop.
Save s0md3v/78ca77b8bfc16649eaa81762039d62c7 to your computer and use it in GitHub Desktop.
concurrency in golang
package main
import (
"sync"
"net/http"
)
func example_function(){
// function to be run concurrently
}
func main(){
var wg sync.WaitGroup // WaitGroups allow your program to wait unitl all goroutines have finished their work
max_procs := make(chan bool, 50) // it's a chnnael, if you try to add more than 50 bool values to it the program will stop executing unless you remove an item from it
for _, item := range items { // iterate over items
go func(item string){ // "go" statement makes a func call to be called async-ly, see line 22 next
wg.Add(1) // add one item to WaitGroup
max_procs<-true // add one item to max_procs channel, if it's the 51th item, the program will pause here, unless you remove some items from max_procs channel
example_function(item) // call your example_function, do your stuff, add more lines here to process the result if you need to
defer wg.Done() // mark this item as done in WaitGroup
<-max_procs // remove one item from max_procs, hence allow more items to be added in
}(item) // you know what it does
}
wg.Wait() // wait (i.e. pause execution) until all the items in the wait group are done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment