Skip to content

Instantly share code, notes, and snippets.

@hosszukalman
Last active May 6, 2020 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hosszukalman/4092cb7cf90c945b50ab07a3f5a24ae5 to your computer and use it in GitHub Desktop.
Save hosszukalman/4092cb7cf90c945b50ab07a3f5a24ae5 to your computer and use it in GitHub Desktop.
Slice fill with go's concurency based on the number of CPUs.
package main
import (
"fmt"
"sync"
)
func makeResult(i int) string {
return fmt.Sprintf("this is %v", i)
}
func main() {
var wg sync.WaitGroup
const sliceLenght = 13
applications := make([]int, sliceLenght, 10000)
appStore := make([]string, len(applications))
numberOfCPUs := 2
incrementer := len(applications) / numberOfCPUs
odd := len(applications) % numberOfCPUs
moreCPUsThanListLenght := false
if numberOfCPUs > len(applications) {
moreCPUsThanListLenght = true
}
if moreCPUsThanListLenght {
fmt.Println("More CPUs than the slice lenght")
for i := range applications {
wg.Add(1)
go func(i int) {
defer wg.Done()
appStore[i] = makeResult(i)
}(i)
}
} else {
fmt.Println("Less CPUs than the slice lenght")
for i := 1; i <= numberOfCPUs; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
start := (i-1)*incrementer + odd
if i == 1 {
start = 0
}
end := i*incrementer + odd
for j := start; j < end; j++ {
appStore[j] = makeResult(j)
}
}(i)
}
}
wg.Wait()
// Let's test the result slice.
for i := 0; i < sliceLenght; i++ {
if appStore[i] != makeResult(i) {
fmt.Printf("the result is not ok in %d, the result is '%v' but it should be '%v'\n", i, appStore[i], makeResult(i))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment