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


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 <pthread.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 10
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) typedef struct struct_max {
   int start;
   int end;
   int thread_num;
} 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 thread_num = s_max->thread_num;
   int cur_max_value = INT_MIN;
   for (int i = start; i < end; ++i) {
      if (arr[i] > cur_max_value) {
         cur_max_value = arr[i];
      }
   }
   max_values_from_threds[thread_num] = cur_max_value;
   return NULL;
}
int main() {
   int total_elements = SIZE(arr);
   int n_threads = 4;
   struct_max thread_arr[4];
   for (int i = 0; i < 4; ++i) {
      thread_arr[i].thread_num = i + 1;
      thread_arr[i].start = i * 4;
      thread_arr[i].end = thread_arr[i].start + 4;
   }
   pthread_t threads[4];
   for (int i = 0; i < 4; ++i) {
      pthread_create(&threads[i], NULL, thread_fun, &thread_arr[i]);
   }
   for (int i = 0; i < 4; ++i) {
      pthread_join(threads[i], NULL);
   }
   int final_max_val = max_values_from_threds[0];
   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

Updated on: 10-Jan-2020

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements