I have this code but it has an error: Segmentation Fault(core dumped) and it doesn't work with more the 2 threads. Any idea of what am i doing wrong?
This code is for calculate pi by Leibniz formula
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>
#define NUM_HILOS 2
struct datos
{
int inicio;
int fin;
float *pi;
}
*calcPi (void *datos){
struct datos *datos_proceso;
datos_proceso = (struct datos *) datos;
int i = datos_proceso -> inicio;
int end = datos_proceso -> fin;
printf("inicio %d \n", i);
printf("fin %d \n", end);
float *pi = datos_proceso -> pi;
int signo = 1;
do{
*pi = *pi +(signo*4.0)/((2*i)+1);
i++;
signo *= -1;
//printf("%f \n", *pi);
}while(i<end);
}
int main()
{
int error, i;
float *pi;
int j = -1;
/*variable para hilos*/
I think that the error is over here but i don't know how to fix it
struct datos hilo_datos[NUM_HILOS];
pthread_t idhilo[NUM_HILOS];
//printf("este es pi %f \n", *pi);
for(i=0; i<NUM_HILOS; i++)
{
hilo_datos[i].inicio =j+1;
hilo_datos[i].fin =j+1000;
hilo_datos[i].pi = pi;
printf("%d \n", hilo_datos[i].inicio);
printf("%d \n", hilo_datos[i].fin);
j += 1000;
}
for(i=0; i<NUM_HILOS; i++)
{
error=pthread_create(&idhilo[i], NULL, (void *)calcPi, &hilo_datos[i]);
}
for(i=0; i<NUM_HILOS; i++)
{
pthread_join(idhilo[i], NULL);
}
printf("este es pi %f \n", *pi);
return 0;
}
malloclike thisstruct datos* hilo_datos = (struct datos*) malloc(NUM_HILOS * sizeof (struct datos));)? - Fiddling Bitshilo_datos[i]. - roelandhilo_datos[i].pi = pi;.piis an uninitialised variable. That is, you have not allocated any memory forpiand then you dereference it within the thread code. - kaylumfloat *piand the memory it pointed to were correctly initialized, it would still be undefined behavior due to unsynchronized writes to it in multiple threads. - EOF