#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h>
#include <errno.h>
#include <time.h>

void *rand_num(){
    float x = drand48()*10.1;
    printf("    |HEBRA HIJA| : Numero x=%.3f \n", x);
    float y = drand48()*10.1;
    printf("    |HEBRA HIJA| : Numero y=%.3f \n", y);

    double * z = malloc(sizeof(double));
    *z=x+y;
    printf("    |HEBRA HIJA| : Suma=%.3f\n", *z);

    pthread_exit((void*) z);
}

int main(int argc, char **argv){
    int num_threads = atoi(argv[1]);
    pthread_t threads[num_threads];
    int error, valor_join;
    double *ret;
    double valor=0;

    srand48 (time(NULL));
    for(int t=0;t<num_threads;t++) 
	{
		printf("|HEBRA PADRE| : Creando hebra %d...\n", t);
		error = pthread_create(&threads[t], NULL, (void *) rand_num, NULL);

       	if (error) 
		{
		    perror("Error joining thread\n");
            printf("errno value= %d\n", errno); 
            exit(EXIT_FAILURE);
		}
	}

    for(int i=0;i<num_threads;i++) 
	{
	    valor_join = pthread_join(threads[i], (void**)&ret);

	    if(valor_join!=0)
	    {
	      perror("Fallo en pthread_join()...\n");		
	      exit(EXIT_FAILURE);
	    }

        valor+=*ret;
	}
    
    printf("|HEBRA PADRE| : Suma total=%.3f...\n", valor);

}