Skip to content

Instantly share code, notes, and snippets.

@hackerpain
Forked from s0md3v/concurrency.go
Created June 29, 2020 17:47
Show Gist options
  • Save hackerpain/9bed1932a57823329a0a77226427cf87 to your computer and use it in GitHub Desktop.
Save hackerpain/9bed1932a57823329a0a77226427cf87 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