# Maximum element in a very large array using pthreads in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

## Problem statement

Given a very large array of integers, find maximum within the array using multithreading

## Example

If input array is {10, 14, -10, 8, 25, 46, 85, 1673, 63, 65, 93, 101, 125, 50, 73, 548} then

maximum element in this array is 1673

## Algorithm

• Let us call array size as total_elements
• Create N threads
• Each thread will process (total_elementes/N) array elements and will find maximum element from it.
• Finally compute the maximum from the maximum value reported by each thread.

## Example

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 10
#define SIZE(arr) (sizeof(arr) / sizeof(arr)) typedef struct struct_max {
int start;
int end;
} struct_max;
int arr[] = {10, 14, -10, 8, 25, 46, 85, 1673, 63, 65, 93, 101, 125, 50, 73, 548};
int max_values_from_threds[MAX];
void *thread_fun(void *arg) {
struct_max *s_max = (struct_max*)arg;
int start = s_max->start;
int end = s_max->end;
int cur_max_value = INT_MIN;
for (int i = start; i < end; ++i) {
if (arr[i] > cur_max_value) {
cur_max_value = arr[i];
}
}
return NULL;
}
int main() {
int total_elements = SIZE(arr);
int n_threads = 4;
for (int i = 0; i < 4; ++i) {
thread_arr[i].start = i * 4;
}
for (int i = 0; i < 4; ++i) {
}
for (int i = 0; i < 4; ++i) {
}
int final_max_val = max_values_from_threds;
for (int i = 0; i < n_threads; ++i) {
if (max_values_from_threds[i] > final_max_val) {
final_max_val = max_values_from_threds[i];
}
}
printf("Maximum value = %d\n", final_max_val);
return 0;
}

## Output

When you compile and execute above program. It generates following output −

Maximum value = 1673