I'm currently trying to use threads to get the max and min of a large array (only have max right now). I'm have an issue with my output though. When I run my program, I get a HUGE number, even after putting a range for the random number. I'm getting numbers like 2147483644 and 2147483606. I would like it to be a range from 0/1 to 1000, but I just don't seem to be getting the right output. Any ideas?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// Size of array
#define size 100000000
// Max number of thread
#define Th_max 4
// Array
int a[size];
// 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 * (size / 4); i < (num + 1) * (size / 4); i++) {
if (a[i] > maxs)
maxs = a[i];
}
max_num[num] = maxs;
}
void fillArray()
{
for (int i = 0; i < size; i++)
{
a[i] = rand() % 1000 + 1;
}
}
// Driver code
int main()
{
int maxs = 0;
int i;
pthread_t threads[Th_max];
fillArray();
for(int i = 0; i < 100000000; i++)
{
a[i] = rand();
}
// 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("Maximun Element is : %d", maxs);
return 0;
}
Thank you.
Aucun commentaire:
Enregistrer un commentaire