Skip to content

Instantly share code, notes, and snippets.

@manjeettahkur
Last active June 5, 2022 09:36
Show Gist options
  • Save manjeettahkur/aec616334f3da3b821e8cfdfe439e67e to your computer and use it in GitHub Desktop.
Save manjeettahkur/aec616334f3da3b821e8cfdfe439e67e to your computer and use it in GitHub Desktop.
This is an example using the Go programming language. With channels With Waitgroups and With Sequentials
func addConcurrent(numbers []int) int {
var v int64
goroutines := runtime.NumCPU()
totalNumbers := len(numbers)
lastGoroutine := goroutines - 1
stride := totalNumbers / goroutines
var wg sync.WaitGroup
wg.Add(goroutines)
for g := 0; g < goroutines; g++ {
go func(g int) {
start := g * stride
end := start + stride
if g == lastGoroutine {
end = totalNumbers
}
var lv int
for _, n := range numbers[start:end] {
lv += n
}
atomic.AddInt64(&v, int64(lv))
wg.Done()
}(g)
}
wg.Wait()
return int(v)
}
func sumArraySequential(a []int) int {
sum := 0
for _, v := range a {
sum += v
}
return sum
}
package main
import (
"fmt"
"math/rand"
"runtime"
"sync"
"sync/atomic"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
fmt.Println(sumArrayConcurrent(GenerateList
(100000)))
}
func sumArrayConcurrent(a []int) int {
totalNumbers := len(a)
goroutines := runtime.NumCPU()
chunk := totalNumbers / goroutines
c := make(chan int)
for i := 0; i < goroutines; i++ {
go func(i int) {
start := i * chunk
end := start + chunk
if i == goroutines-1 {
end = totalNumbers
}
sum(a[start:end], c)
}(i)
}
var total int
for i := 0; i < goroutines; i++ {
total += <-c
}
close(c)
return total
}
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum // send sum to c
}
func GenerateList(totalNumbers int) []int {
numbers := make([]int, totalNumbers)
for i := 0; i < totalNumbers; i++ {
numbers[i] = rand.Intn(totalNumbers)
}
return numbers
}
@manjeettahkur
Copy link
Author

This is an example using the Go programming language.

  1. With channels
  2. With Waitgroups
  3. Sequentials

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment