Maximum element in a very large array using pthreads
Last Updated :
27 Dec, 2023
Given a very large array of integers, find maximum within the array using multithreading.
Examples:
Input : 1, 5, 7, 10, 12, 14, 15, 18, 20,
22, 25, 27, 30, 64, 110, 220
Output :Maximum Element is : 220Input : 10, 50, 70, 100, 120, 140, 150, 180,
200, 220, 250, 270, 300, 640, 110, 220
Output : Maximum Element is : 640
Prerequisite : Multithreading Note : Useful in large files of size MB/GB.
How to run : It can only be run on linux envirenment. command :
>> gcc -pthread maximum.c
>> ./a.out
C++
// C++ code to find maximum of an array using Multithreading
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// Size of array
#define max 16
// Max number of threads
#define Th_max 4
// Array
int a[max] = { 1, 5, 7, 10, 12, 14, 15, 18, 20,
22, 25, 27, 300, 64, 110, 220 };
// Array to store max of threads
int max_num[Th_max] = { 0 };
int thread_no = 0;
// Function to find maximum
void* maximum(void* arg)
{
int i, num = thread_no++;
int maxs = 0;
for (i = num * (max / 4); i < (num + 1) * (max / 4); i++) {
if (a[i] > maxs)
maxs = a[i];
}
max_num[num] = maxs;
}
// Driver code
int main()
{
int maxs = 0;
int i;
pthread_t threads[Th_max];
// creating 4 threads
for (i = 0; i < Th_max; i++)
pthread_create(&threads[i], NULL, maximum, (void*)NULL);
// joining 4 threads i.e. waiting for
// all 4 threads to complete
for (i = 0; i < Th_max; i++)
pthread_join(threads[i], NULL);
// Finding max element in an array
// by individual threads
for (i = 0; i < Th_max; i++) {
if (max_num[i] > maxs)
maxs = max_num[i];
}
printf("Maximum Element is : %d", maxs);
return 0;
}
// This code is contributed by Shivhack999
C
// C++ code to find maximum of an array using Multithreading
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// Size of array
#define max 16
// Max number of thread
#define Th_max 4
// Array
int a[max] = { 1, 5, 7, 10, 12, 14, 15, 18, 20,
22, 25, 27, 300, 64, 110, 220 };
// Array to store max of threads
int max_num[Th_max] = { 0 };
int thread_no = 0;
// Function to find maximum
void maximum(void* arg)
{
int i, num = thread_no++;
int maxs = 0;
for (i = num * (max / 4); i < (num + 1) * (max / 4); i++) {
if (a[i] > maxs)
maxs = a[i];
}
max_num[num] = maxs;
}
// Driver code
int main()
{
int maxs = 0;
int i;
pthread_t threads[Th_max];
// creating 4 threads
for (i = 0; i < Th_max; i++)
pthread_create(&threads[i], NULL,
maximum, (void*)NULL);
// joining 4 threads i.e. waiting for
// all 4 threads to complete
for (i = 0; i < Th_max; i++)
pthread_join(threads[i], NULL);
// Finding max element in an array
// by individual threads
for (i = 0; i < Th_max; i++) {
if (max_num[i] > maxs)
maxs = max_num[i];
}
printf("Maximum Element is : %d", maxs);
return 0;
}
Java
import java.util.Arrays;
public class MaxElementThread extends Thread {
int lo, hi;
int[] arr;
int max;
public MaxElementThread(int[] arr, int lo, int hi) {
this.arr = arr;
this.lo = lo;
this.hi = hi;
this.max = Integer.MIN_VALUE;
}
public void run() {
for (int i = lo; i < hi; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
}
public static void main(String[] args) {
int[] arr = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 300, 64, 110, 220 };
int n = arr.length;
int numThreads = 4;
MaxElementThread[] threads = new MaxElementThread[numThreads];
int blockSize = n / numThreads;
for (int i = 0; i < numThreads; i++) {
int lo = i * blockSize;
int hi = (i == numThreads - 1) ? n : (i + 1) * blockSize;
threads[i] = new MaxElementThread(arr, lo, hi);
threads[i].start();
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < numThreads; i++) {
try {
threads[i].join();
if (threads[i].max > max) {
max = threads[i].max;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Maximum Element is : " + max);
}
}
Python3
# C++ code to find maximum of an array using Multithreading
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, 300, 64, 110, 220]
# Max array for storing max of each part computed
max_num = [0 for _ in range(MAX_THREAD)]
thread_no = 0
# Function to calculate maximum
def maximum():
global thread_no
index = thread_no
thread_no += 1
# Each thread computes max of 1/4th of array
start, end = int(index*(MAX/4)), int((index+1)*(MAX/4))
for i in range(start, end, 1):
max_num[index] = max(max_num[index], 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=maximum)
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_max = 0
for x in max_num:
actual_max = max(actual_max, x)
print("Maximum element is : %d" % actual_max)
C#
using System;
using System.Threading;
public class MaxArrayThread
{
// 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, 300, 64, 110, 220 };
// Max array for storing max of each part computed
static int[] max_num = new int[MAX_THREAD];
static int thread_no = 0;
// Function to calculate maximum
static void Maximum()
{
int index = Interlocked.Increment(ref thread_no) - 1;
// Each thread computes max of 1/4th of array
int start = (int)(index * (MAX / 4));
int end = (int)((index + 1) * (MAX / 4));
for (int i = start; i < end; i++)
{
max_num[index] = Math.Max(max_num[index], arr[i]);
}
}
public static void Main()
{
// Creating array of size MAX_THREAD
Thread[] thread = new Thread[MAX_THREAD];
// Creating MAX_THREAD number of threads
for (int i = 0; i < MAX_THREAD; i++)
{
thread[i] = new Thread(Maximum);
thread[i].Start();
}
// Waiting for all threads to finish
for (int i = 0; i < MAX_THREAD; i++)
{
thread[i].Join();
}
// Adding sum of all 4 parts
int actual_max = 0;
for (int i = 0; i < MAX_THREAD; i++)
{
actual_max = Math.Max(actual_max, max_num[i]);
}
Console.WriteLine("Maximum element is : {0}", actual_max);
}
}
// This code is contributed by shivregkec
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, 300, 64, 110, 220];
// Max array for storing max of each part computed
const maxNum = new Array(MAX_THREAD).fill(0);
let threadNo = 0;
// Function to calculate maximum
function maximum() {
const index = threadNo;
threadNo += 1;
// Each thread computes max of 1/4th of array
const start = Math.floor(index * (MAX / 4));
const end = Math.floor((index + 1) * (MAX / 4));
for (let i = start; i < end; i++) {
maxNum[index] = Math.max(maxNum[index], arr[i]);
}
}
// Creating MAX_THREAD number of threads
const threads = new Array(MAX_THREAD).fill(null).map(() => {
return new Promise(resolve => {
maximum();
resolve();
});
});
// Waiting for all threads to finish
Promise.all(threads).then(() => {
// Adding max of all 4 parts
const actualMax = maxNum.reduce((max, x) => Math.max(max, x), 0);
console.log(`Maximum element is: ${actualMax}`);
});
OutputMaximum element is : 300
Similar Reads
Program to find largest element in an array using Dynamic Memory Allocation
Given an array arr[] consisting of N integers, the task is to find the largest element in the given array using Dynamic Memory Allocation. Examples: Input: arr[] = {4, 5, 6, 7} Output: 7Explanation:The largest element present in the given array is 7. Input: arr[] = {8, 9, 10, 12} Output: 12Explanati
5 min read
How to Find Maximum Value in an Array in C?
In C, arrays are data structures that allow the user to store a collection of data of the same type. In this article, we will learn how we can find the maximum value in an array in C. Example Input: arr = {5,3,1,2,4} Output: The maximum value of the array is: 5Finding Maximum Value in an Array in CW
2 min read
Maximum element in a sorted and rotated array
Given a sorted array arr[] (may contain duplicates) of size n that is rotated at some unknown point, the task is to find the maximum element in it. Examples: Input: arr[] = {5, 6, 1, 2, 3, 4}Output: 6Explanation: 6 is the maximum element present in the array.Input: arr[] = {3, 2, 2, 2}Output: 3Expla
7 min read
Find the maximum element in the array other than Ai
Given an array arr[] of size N. The task is to find maximum element among N - 1 elements other than arr[i] for each i from 1 to N.Examples: Input: arr[] = {2, 5, 6, 1, 3} Output: 6 6 5 6 6 Input: arr[] = {1, 2, 3} Output: 3 3 2 Approach: An efficient approach is to make prefix and suffix array of ma
6 min read
Find the element having maximum premutiples in the array
Given an array arr[], the task is to find the element which has the maximum number of pre-multiples present in the set. For any index i, pre-multiple is the number that is multiple of i and is present before the ith index of the array. Also, print the count of maximum multiples of that element in th
8 min read
Find element with the maximum set bits in an array
Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.Examples: Input: arr[] = {10, 100, 1000, 10000} Output: 1000 Binary(10) = 1010 (2 set bits) Binary(100) = 1100100 (3 set bits) Binary(1000) = 1111101000 (6 set bits) Binary(10000) = 10011100010000
5 min read
Largest element in an Array
Given an array arr. The task is to find the largest element in the given array. Examples: Input: arr[] = [10, 20, 4]Output: 20Explanation: Among 10, 20 and 4, 20 is the largest. Input: arr[] = [20, 10, 20, 4, 100]Output: 100Table of ContentIterative Approach - O(n) Time and O(1) SpaceRecursive Appro
6 min read
Reading and writing in the array using threads
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the arr
6 min read
Tracking current Maximum Element in a Stack
Given a Stack, keep track of the maximum value in it. The maximum value may be the top element of the stack, but once a new element is pushed or an element is popped from the stack, the maximum element will be now from the rest of the elements. Examples: Input : 4 19 7 14 20Output : Max Values in st
6 min read
Maximize elements using another array
Given two arrays a[] and b[] of size n. The task is to maximize the first array by using the elements from the second array such that the new array formed contains n greatest but unique elements of both the arrays giving the second array priority (All elements of second array appear before first arr
15 min read