I created two thread the job of the first thread is to sum up the array and print it out and the job of the second thread is to find the product of the array and print it out the two thread read the array from a txt file my program is hard coded I have an array size of 40 the problem is every time I run my code I get the same output even though I change some numbers in my array it should give me different value depending on every time I change any number in the array my main problem is in the part that read from a file my program works will without reading form a file
#include <stdio.h>
#include <pthread.h>
int array[40];
int sum = 0;
long long int product = 1;
//function to read file
void read_ints(const char* file_name)
{
FILE* file = fopen(file_name, "r");
int i = 0;
int j = 0;
fscanf(file, "%d", &i);
while (!feof(file)) {
array[j] = i;
j++;
fscanf(file, "%d", &i);
fscanf(file, "%d", &i);
}
array[j] = i;
fclose(file);
}
void* sum_array(void* arg)
{
for (int i = 0; i < 40; i++)
sum += array[i];
}
void* product_array(void* arg)
{
for (int i = 0; i < 40; i++)
product *= array[i];
}
int main()
{
read_ints("input.txt");
pthread_t threads[2];
pthread_create(&threads[0], NULL, sum_array, (void*)NULL);
pthread_create(&threads[1], NULL, product_array, (void*)NULL);
for (int i = 0; i < 2; i++)
pthread_join(threads[i], NULL);
printf("sum is: %d \n", sum);
printf("product is: %lli \n", product);
return 0;
}
the following is the compilation:
gcc yyy.c -o yyy -lpthread
./yyy input.txt
the output I get every time is
sum is: 1022
product is: -2987895910446399488