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 600Input : 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
// 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;
}
Java
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
# 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#
// 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
JavaScript
// 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)
Similar Reads
Addition and Subtraction of Matrix using pthreads
Addition or Subtraction of matrices takes O(n^2) time without threads but using threads we don't reduce the time complexity of the program we divide the task into core like if we have 4 core then divide the matrix into 4 part and each core take one part of the matrix and compute the operations and f
13 min read
Frequency of a substring in a string using pthread
Given an input string and a substring. Find the frequency of occurrences of a substring in the given string using pthreads. Examples: Input: string = "man" substring = "dhimanman"Output: 2Input: string = "banana" substring = "nn"Output: 0Note: It is advised to execute the program in Linux based syst
6 min read
Sum of unique sub-array sums
Given an array of n-positive elements. The sub-array sum is defined as the sum of all elements of a particular sub-array, the task is to find the sum of all unique sub-array sum. Note: Unique Sub-array sum means no other sub-array will have the same sum value. Examples:Input : arr[] = {3, 4, 5} Outp
8 min read
A Sum Array Puzzle
Given an array arr[] of n integers, construct a Sum Array sum[] (of same size) such that sum[i] is equal to the sum of all the elements of arr[] except arr[i]. Solve it without subtraction operator and in O(n). Examples: Input : arr[] = {3, 6, 4, 8, 9} Output : sum[] = {27, 24, 26, 22, 21} Input : a
15 min read
Split an array into two equal Sum subarrays
Given an array of integers greater than zero, find if it is possible to split it in two subarrays (without reordering the elements), such that the sum of the two subarrays is the same. Print the two subarrays. Examples : Input : Arr[] = { 1 , 2 , 3 , 4 , 5 , 5 } Output : { 1 2 3 4 } { 5 , 5 } Input
15 min read
Sum of all prime numbers in an Array
Given an array arr[] of N positive integers. The task is to write a program to find the sum of all prime elements in the given array. Examples: Input: arr[] = {1, 3, 4, 5, 7} Output: 15 There are three primes, 3, 5 and 7 whose sum =15. Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 17 Naive Approach:
7 min read
Program to print Sum Triangle for a given array
Given a array, write a program to construct a triangle where last row contains elements of given array, every element of second last row contains sum of below two elements and so on. Example: Input: arr[] = {4, 7, 3, 6, 7};Output:8140 4121 19 2211 10 9 134 7 3 6 7 Input: {10, 40, 50}Output:14050 901
9 min read
Sum of every Kâth prime number in an array
Given an integer k and an array of integers arr (less than 10^6), the task is to find the sum of every kâth prime number in the array. Examples: Input: arr[] = {2, 3, 5, 7, 11}, k = 2 Output: 10 All the elements of the array are prime. So, the prime numbers after every K (i.e. 2) interval are 3, 7 a
9 min read
Sum of every K'th prime number in an array
Given an array of integers (less than 10^6), the task is to find the sum of all the prime numbers which appear after every (k-1) prime number i.e. every K'th prime number in the array. Examples: Input : Array : 2, 3, 5, 7, 11 ; n=5; k=2 Output : Sum = 10 Explanation: All the elements of the array ar
7 min read
Find sum of factorials in an array
Given an array arr[] of N integers. The task is to find the sum of factorials of each element of the array. Examples: Input: arr[] = {7, 3, 5, 4, 8} Output: 45510 7! + 3! + 5! + 4! + 8! = 5040 + 6 + 120 + 24 + 40320 = 45510 Input: arr[] = {2, 1, 3} Output: 9 Approach: Implement a function factorial(
8 min read