I try to throw an array of 10 numbers from 1 to 100 to pthread for find min, max and avg number.
I print the values of the array before I throw it.
The values have correct values.
But sometimes it has wrong valves like -209574485
or 65271552
.
The wrong values only show up when the array is thrown to pthread.
My code is as follows:
#define N 3
#define MAXSize 10
void *min_thread(void *arg)
{
int *test = (int*)arg;
int min;
for (int i = 1; i <= MAXSize; i++) {
if (test[i] < min) {
min = test[i];
}
}
printf("Min number is : %d\n", min);
}
void *max_thread(void *arg)
{
int *test = (int*)arg;
int max;
for (int i = 1; i <= MAXSize; i++) {
if (test[i] > max) {
max = test[i];
}
}
printf("Max number is : %d\n", max);
}
void *Avg_thread(void *arg) {
int *test = (int*)arg;
int avg;
for (int i = 1; i <= MAXSize; i++) {
avg += test[i];
}
avg = avg / MAXSize;
printf("Avg number is : %d\n", avg);
}
int main(int argc, char *argv[])
{
srand(time(NULL));
int random_number[MAXSize];
int min, max, avg;
for (int i = 0; i < MAXSize; i++) {
random_number[i] = rand() % 100 + 1;
printf("%d\n", random_number[i]);
}
pthread_t my_thread[N];
pthread_create(&my_thread[1], NULL, min_thread, (void*)&random_number);
pthread_create(&my_thread[2], NULL, max_thread, (void*)&random_number);
pthread_create(&my_thread[3], NULL, Avg_thread, (void*)&random_number);
pthread_exit(NULL);
return 0;
}
The result I get from this code:
93
52
72
79
37
96
26
15
86
42
Min number is : -963189760
Avg number is : -96318925
Max number is : 96