Last active
February 12, 2022 15:09
-
-
Save 0xInfection/675153c17b2174f271a3a7efbf73f5f4 to your computer and use it in GitHub Desktop.
Example code which implements go concurrency
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
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