
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compute Sum of Integers Using Concurrency in Go
In this Go language article, we will write programs to take in a slice of integers and compute their sum using concurrency. Concurrency helps multiple tasks or operations to be performed simultaneously. It helps make efficient use of system resources. It is achieved using Go routines which are light-weight threads and channels which helps in the communication between the go routines.
Syntax
func make ([] type, size, capacity)
The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments.
func range(variable)
The range function is used to iterate over any data type. To use this we first have to write the range keyword followed by the data type to which we want to iterate and as a result the loop will iterate till the last element of the variable.
func len(v Type) int
The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.
Algorithm
This program imports fmt, main and sync as necessary packages where fmt helps in the input /output operations, main helps to produce executable codes and sync helps to achieve concurrency tasks.
Create a function named sum which takes a slice of integers whose sum is to be calculated.
Create a total variable and initialize it to 0.
Then, using the range function interate the slice of integers and in each iteration add the input element to the total variable.
After iterating over all elements return the total as the calculated sum.
In this step, create a concurrent Sum function takes a slice of integers and calculates their sum using concurrency.
Then, determines the number of chunks to divide the input slice into based on the length of the slice and store it inside num-chunks variable.
Then, create a slice sums using make function to store the partial sums calculated by each goroutine
In this step, initialize a sync.Wait Group and add a count equal to the number of chunks to it using the Add method.
Here, calculate the chunk size to evenly divide the input slice.
Then, use a for loop to launch a go routine for each chunk.
Inside each go routine calculate the sum of its corresponding chunk using the sum function and store the result in the sums slice.
In this step, wait for all go routines to complete using wg.Wait() function.
Finally return the calculated sum as the result to the function.
Create a main function.
In the main, a slice of integers named slice is created.
Then, the concurrent_sum function on the slice is called to calculate the sum using concurrency.
The calculated sum is then printed to the console using the Println function from the fmt package where ln means new line.
Example
In this example, we will write a Go language program to calculate the sum of integers in slice with the help of go routines and channels to execute the program concurrently.
package main import ( "fmt" "sync" ) func sum(nums []int) int { total := 0 for _, num := range nums { total += num } return total } func concurrent_sum(nums []int) int { num_chunks := len(nums) sums := make([]int, num_chunks) var wg sync.WaitGroup wg.Add(num_chunks) chunkSize := (len(nums) + num_chunks - 1) / num_chunks for i := 0; i < num_chunks; i++ { go func(i int) { defer wg.Done() start := i * chunkSize end := (i + 1) * chunkSize if end > len(nums) { end = len(nums) } sums[i] = sum(nums[start:end]) }(i) } wg.Wait() return sum(sums) } func main() { slice := []int{10, 20, 30, 40, 50, 60, 70, 80, 90, 100} fmt.Println("Numbers:", slice) total := concurrent_sum(slice) fmt.Println("The Sum of the elements of slice is:", total) }
Output
Numbers: [10 20 30 40 50 60 70 80 90 100] The Sum of the elements of slice is: 550
Conclusion
We compiled and executed the program of calculating the sum of slice of integers using an example that uses go routines and channels to execute a concurrent process. Hence, concurrency is obtained.