I am trying to create a program in C to calculate the sum and the product via threads.It's my exercise for university.The problem I face is that when I run the program the thread doesn't seem to execute.I am stuck and I don't know how to proceed.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int T1; //store the sum
int *array; //global varriable
void *Sum(void *N){ //function used by thread to calculate sum
printf("I am the 1st thread i ll calculate the sum for you");
long S=(long) N;
int sum=0;
int i;
for (i=0; i<S; ++i){
sum = sum +array[i];
}
T1 = sum;
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
long N;
printf("%d\n",T1);
printf("give the size of the array please\n");
scanf("%ld", &N);
int *array= (int*) malloc((N)*sizeof(int)); // dynamic array
int i;
for (i=0; i<N; ++i)
{
array[i]=rand() % 301 + (-150);// creates random numbers from -150 to 150
}
for (i=0; i<N; ++i) {
printf(" %d\n", array[i]);
}
pthread_t Th;
pthread_create(&Th, NULL,Sum, (void*)N); //creates thread
printf("%d\n",T1);
return (0);
}`
I tried changing pthread_exit(NULL);
to return(0)
or return(T1)
but it didn't work. I changed the Sum function to:
void *Sum(void *N){ //function used by thread to calculate sum
printf("I am the 1st thread i ll calculate the sum for you");
pthread_exit(NULL);
}
It didn't work either.the output I get anyway is :
0
give the size of the array please
2
117
113
0
Note that I get no compile errors or warnings.