2
I’m having problems in the following exercise
Write a program that, given a vector with the first 5 numbers primes, pitch 5 threads. Each of them will calculate the value of the factorial of one of the vector positions and replaces that vector’s value position with calculated value. The main thread expects all threads finish, print vector and finish as well.
I have the following resolution
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define NTHREADS 5
void *Fatorial(int *array)
{
printf("***Entrei na função fatorial***\n");
int fat = 0, n = 0;
for(fat = 1; n > 1; n = n - 1)
{
array[n] = array[n] * n;
}
pthread_exit(NULL);
}
int main()
{
printf("Início da função\n");
int *array[5] = {2,3,5,7,11};
int i = 0,rc = 0;
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
printf("Antes do FOR\n");
for(i = 0; i < NTHREADS; i++)
{
rc = array[i];
rc = pthread_create(&tid,&attr,Fatorial,NULL);
if (rc)
{
printf("ERROR - return code from pthread_create() is %d\n", rc);
exit(-1);
}
rc = pthread_join(tid, NULL);
if (rc)
{
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
printf("Array[] = ");
for(i = 0; i < NTHREADS; i++)
{
printf("%d ",array[i]);
}
pthread_attr_destroy(&attr);
pthread_exit(NULL);
return 0;
}
One of my problems is how to have the array calculated in the auxiliary thread (which aims to calculate the factorial of an array position). Testanto with print’s I can notice that the program enters 5 times in the auxiliary thread so I think I am in a correct path. I still don’t understand how to work the array itself.