This is a c program to calculate the factorial of a number using pthread
if I comment the from thread create line to pthread join line, I got a segmentation fault at 2nd iteration...
here is the code
Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <math.h>
typedef struct
{
int ThreadNum;
int n;
int debut;
int fin;
unsigned long long produit;
} Parametres;
void *CalculerProduit(void *data)
{
int debut;
int fin;
int factoriel;
const int N_THREADS = 4;
Parametres * mesParametres = data;
printf("Je suis le thread %d", mesParametres->ThreadNum);
printf(" qui calcule le produit de %d a %d \n",mesParametres->debut, mesParametres->fin);
if ( mesParametres->ThreadNum != N_THREADS) //if not last thread
{
mesParametres->fin = (mesParametres->n / N_THREADS) * mesParametres->ThreadNum;
}
else
{
mesParametres->fin = mesParametres->n;
}
mesParametres->debut= (mesParametres->n /N_THREADS)*(mesParametres->ThreadNum - 1) + 1;
factoriel = mesParametres->debut;
for (int nombre = mesParametres->debut +1; nombre <mesParametres->fin +1; nombre++)
{
factoriel = factoriel * nombre;
}
}
int main(int argc, char *argv[])
{
int n = 16;
int status;
const int N_THREADS = 4;
long long factoriel;
pthread_t threads[N_THREADS];
Parametres * mesParametres[N_THREADS];
for (int i=0; i < N_THREADS; i++)
{
mesParametres[i]->ThreadNum = i+1;
mesParametres[i]->n = n;
printf("Main(): En train de creer le thread %d \n",mesParametres[i]->ThreadNum);
status=pthread_create(&threads[i],NULL,CalculerProduit,(void*)&mesParametres
[i]);
if (status != 0);
{
printf("Oops, une erreure cest produite.");
return(-1);
}
pthread_join(threads[i], NULL);
}
//TODO implement
return 0;
}
ty
