Sum of array is a small problem where we have to add each element in the array by traversing through the entire array. But when the number of elements are too large, it could take a lot of time. But this could solved by dividing the array into parts and finding sum of each part simultaneously i.e. by finding sum of each portion in parallel. This could be done by using multi-threading where each core of the processor is used. In our case, each core will evaluate sum of one portion and finally we will add the sum of all the portion to get the final sum. In this way we could improve the performance of a program as well as utilize the cores of processor. It is better to use one thread for each core. Although you can create as many thread as you want for better understanding of multi-threading. Examples:
Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220
Output : sum is 600
Input : 10, 50, 70, 100, 120, 140, 150, 180, 200, 220, 250, 270, 300, 640, 110, 220
Output : sum is 3030
Note – It is advised to execute the program in Linux based system. Compile in linux using following code:
g++ -pthread program_name.cpp
Code –
// CPP Program to find sum of array #include <iostream> #include <pthread.h> // size of array #define MAX 16 // maximum number of threads #define MAX_THREAD 4 using namespace std;
int a[] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };
int sum[4] = { 0 };
int part = 0;
void * sum_array( void * arg)
{ // Each thread computes sum of 1/4th of array
int thread_part = part++;
for ( int i = thread_part * (MAX / 4); i < (thread_part + 1) * (MAX / 4); i++)
sum[thread_part] += a[i];
} // Driver Code int main()
{ pthread_t threads[MAX_THREAD];
// Creating 4 threads
for ( int i = 0; i < MAX_THREAD; i++)
pthread_create(&threads[i], NULL, sum_array, ( void *)NULL);
// joining 4 threads i.e. waiting for all 4 threads to complete
for ( int i = 0; i < MAX_THREAD; i++)
pthread_join(threads[i], NULL);
// adding sum of all 4 parts
int total_sum = 0;
for ( int i = 0; i < MAX_THREAD; i++)
total_sum += sum[i];
cout << "sum is " << total_sum << endl;
return 0;
} |
import java.util.concurrent.*;
class Main {
// Size of array
private static final int MAX = 16 ;
// Maximum number of threads
private static final int MAX_THREAD = 4 ;
private static int [] a = { 1 , 5 , 7 , 10 , 12 , 14 , 15 , 18 , 20 , 22 , 25 , 27 , 30 , 64 , 110 , 220 };
private static int [] sum = new int [MAX_THREAD];
private static int part = 0 ;
static class SumArray implements Runnable {
@Override
public void run() {
// Each thread computes sum of 1/4th of array
int thread_part = part++;
for ( int i = thread_part * (MAX / 4 ); i < (thread_part + 1 ) * (MAX / 4 ); i++) {
sum[thread_part] += a[i];
}
}
}
// Driver Code
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[MAX_THREAD];
// Creating 4 threads
for ( int i = 0 ; i < MAX_THREAD; i++) {
threads[i] = new Thread( new SumArray());
threads[i].start();
}
// Joining 4 threads i.e. waiting for all 4 threads to complete
for ( int i = 0 ; i < MAX_THREAD; i++) {
threads[i].join();
}
// Adding sum of all 4 parts
int total_sum = 0 ;
for ( int i = 0 ; i < MAX_THREAD; i++) {
total_sum += sum[i];
}
System.out.println( "sum is " + total_sum);
}
} |
# Python3 Program to find sum of array # using multi-threading from threading import Thread
# Size of array MAX = 16
# Maximum number of threads MAX_THREAD = 4
# Initial array arr = [ 1 , 5 , 7 , 10 , 12 , 14 , 15 , 18 , 20 , 22 , 25 , 27 , 30 , 64 , 110 , 220 ]
# Sum array for storing sum of each part computed sum_arr = [ 0 for _ in range (MAX_THREAD)]
part = 0
def sum_array():
global part
thread_part = part
part = part + 1
# Each thread computes sum of 1/4th of array
thread_start = int (thread_part * ( MAX / 4 ))
thread_end = int ((thread_part + 1 ) * ( MAX / 4 ))
for i in range (thread_start, thread_end, 1 ):
sum_arr[thread_part] = sum_arr[thread_part] + arr[i]
if __name__ = = "__main__" :
# Creating list of size MAX_THREAD
thread = list ( range (MAX_THREAD))
# Creating MAX_THEAD number of threads
for i in range (MAX_THREAD):
thread[i] = Thread(target = sum_array)
thread[i].start()
# Waiting for all threads to finish
for i in range (MAX_THREAD):
thread[i].join()
# Adding sum of all 4 parts
actual_sum = 0
for x in sum_arr:
actual_sum = actual_sum + x
print ( "Sum is %d" % actual_sum)
|
// C# Program to find sum of array // using multi-threading using System;
using System.Threading;
class Program
{ // Size of array const int MAX = 16;
// Maximum number of threads const int MAX_THREAD = 4;
// Initial array static int [] arr = new int [] { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };
// Sum array for storing sum of each part computed static int [] sum_arr = new int [MAX_THREAD];
static int part = 0;
static void SumArray()
{ // Each thread computes sum of 1/4th of array
int thread_part = Interlocked.Increment( ref part) - 1;
int thread_start = ( int )(thread_part * (MAX / 4));
int thread_end = ( int )((thread_part + 1) * (MAX / 4));
for ( int i = thread_start; i < thread_end; i++)
{
Interlocked.Add( ref sum_arr[thread_part], arr[i]);
}
} static void Main( string [] args)
{ // Creating list of size MAX_THREAD
Thread[] threads = new Thread[MAX_THREAD];
// Creating MAX_THEAD number of threads
for ( int i = 0; i < MAX_THREAD; i++)
{
threads[i] = new Thread( new ThreadStart(SumArray));
threads[i].Start();
}
// Waiting for all threads to finish
for ( int i = 0; i < MAX_THREAD; i++)
{
threads[i].Join();
}
// Adding sum of all 4 parts
int actual_sum = 0;
for ( int i = 0; i < MAX_THREAD; i++)
{
actual_sum += sum_arr[i];
}
Console.WriteLine( "Sum is {0}" , actual_sum);
} } //This code is contributed by shivhack999 |
// Size of array const MAX = 16; // Maximum number of threads const MAX_THREAD = 4; // Initial array const arr = [1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220]; // Sum array for storing sum of each part computed const sumArr = new Array(MAX_THREAD).fill(0);
let part = 0; function sumArray() {
const threadPart = part;
part = part + 1;
// Each thread computes sum of 1/4th of array
const threadStart = Math.floor(threadPart * (MAX / 4));
const threadEnd = Math.floor((threadPart + 1) * (MAX / 4));
for (let i = threadStart; i < threadEnd; i++) {
sumArr[threadPart] += arr[i];
}
} // Creating MAX_THREAD number of threads const threads = new Array(MAX_THREAD).fill( null ).map(() => {
return new Promise(resolve => {
sumArray();
resolve();
});
}); // Waiting for all threads to finish Promise.all(threads).then(() => { // Adding sum of all 4 parts
const actualSum = sumArr.reduce((sum, x) => sum + x, 0);
console.log(`Sum is ${actualSum}`);
}); |
Output:
sum is 600
Time Complexity: O(MAX_THREAD)
Auxiliary Space: O(1)