Skip to content

Instantly share code, notes, and snippets.

@0xInfection
Last active February 12, 2022 15:09
Show Gist options
  • Save 0xInfection/675153c17b2174f271a3a7efbf73f5f4 to your computer and use it in GitHub Desktop.
Save 0xInfection/675153c17b2174f271a3a7efbf73f5f4 to your computer and use it in GitHub Desktop.
Example code which implements go concurrency
import "sync"
func exampleFunc(str string) {
// function to run concurrently
}
func main() {
threadVal := 50 // number of threads to use
allItems := []string{} // the slice containing whatever you want to pass to exampleFunc
// creating a channel of strings, use whatever type the exampleFunc() takes in
items := make(chan string, threadVal) // threadVal is the number of threads to use
maxProcs := new(sync.WaitGroup) // creating a sync.WaitGroup instance
maxProcs.Add(threadVal) // add the number of threads to the instance
for i := 0; i < threadVal; i++ { // looping over the threads
go func() { // a normal goroutine
for {
host := <-items // extracting a item from the channel
exampleFunc(host) // toss over the value to exampleFunc(), or your function
}
maxProcs.Done() // the work is over
}()
}
for _, items := range allItems {
items <- item // add an item from the allItems slice
}
close(item) // close the channel
maxProcs.Wait() // wait for all goroutines to complete
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment