Sum of an array using pthreads
Last Updated :
27 Dec, 2023
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
#include <iostream>
#include <pthread.h>
#define MAX 16
#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)
{
int thread_part = part++;
for ( int i = thread_part * (MAX / 4); i < (thread_part + 1) * (MAX / 4); i++)
sum[thread_part] += a[i];
}
int main()
{
pthread_t threads[MAX_THREAD];
for ( int i = 0; i < MAX_THREAD; i++)
pthread_create(&threads[i], NULL, sum_array, ( void *)NULL);
for ( int i = 0; i < MAX_THREAD; i++)
pthread_join(threads[i], NULL);
int total_sum = 0;
for ( int i = 0; i < MAX_THREAD; i++)
total_sum += sum[i];
cout << "sum is " << total_sum << endl;
return 0;
}
|
Java
import java.util.concurrent.*;
class Main {
private static final int MAX = 16 ;
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() {
int thread_part = part++;
for ( int i = thread_part * (MAX / 4 ); i < (thread_part + 1 ) * (MAX / 4 ); i++) {
sum[thread_part] += a[i];
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[MAX_THREAD];
for ( int i = 0 ; i < MAX_THREAD; i++) {
threads[i] = new Thread( new SumArray());
threads[i].start();
}
for ( int i = 0 ; i < MAX_THREAD; i++) {
threads[i].join();
}
int total_sum = 0 ;
for ( int i = 0 ; i < MAX_THREAD; i++) {
total_sum += sum[i];
}
System.out.println( "sum is " + total_sum);
}
}
|
Python3
from threading import Thread
MAX = 16
MAX_THREAD = 4
arr = [ 1 , 5 , 7 , 10 , 12 , 14 , 15 , 18 , 20 , 22 , 25 , 27 , 30 , 64 , 110 , 220 ]
sum_arr = [ 0 for _ in range (MAX_THREAD)]
part = 0
def sum_array():
global part
thread_part = part
part = part + 1
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__" :
thread = list ( range (MAX_THREAD))
for i in range (MAX_THREAD):
thread[i] = Thread(target = sum_array)
thread[i].start()
for i in range (MAX_THREAD):
thread[i].join()
actual_sum = 0
for x in sum_arr:
actual_sum = actual_sum + x
print ( "Sum is %d" % actual_sum)
|
C#
using System;
using System.Threading;
class Program
{
const int MAX = 16;
const int MAX_THREAD = 4;
static int [] arr = new int [] { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };
static int [] sum_arr = new int [MAX_THREAD];
static int part = 0;
static void SumArray()
{
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)
{
Thread[] threads = new Thread[MAX_THREAD];
for ( int i = 0; i < MAX_THREAD; i++)
{
threads[i] = new Thread( new ThreadStart(SumArray));
threads[i].Start();
}
for ( int i = 0; i < MAX_THREAD; i++)
{
threads[i].Join();
}
int actual_sum = 0;
for ( int i = 0; i < MAX_THREAD; i++)
{
actual_sum += sum_arr[i];
}
Console.WriteLine( "Sum is {0}" , actual_sum);
}
}
|
Javascript
const MAX = 16;
const MAX_THREAD = 4;
const arr = [1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220];
const sumArr = new Array(MAX_THREAD).fill(0);
let part = 0;
function sumArray() {
const threadPart = part;
part = part + 1;
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];
}
}
const threads = new Array(MAX_THREAD).fill( null ).map(() => {
return new Promise(resolve => {
sumArray();
resolve();
});
});
Promise.all(threads).then(() => {
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...