Last active
June 5, 2022 09:36
-
-
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
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
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) | |
} |
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
func sumArraySequential(a []int) int { | |
sum := 0 | |
for _, v := range a { | |
sum += v | |
} | |
return sum | |
} |
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
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 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an example using the Go programming language.