Ver Mensaje Individual
  #1 (permalink)  
Antiguo 08/03/2015, 16:32
lacf95
 
Fecha de Ingreso: marzo-2015
Mensajes: 9
Antigüedad: 9 años, 2 meses
Puntos: 0
Pregunta Uso de Threads en C

Hola, soy nuevo en el foro, tengo un problema con los valores que regresan los threads.
El programa debe crear 5 hilos de ejcución. Cada hilo determina un número aleatorio entre 1 y 10. El hilo principal espera a que los hilos terminen, calcula la suma de los números generados aleatoriamente por cada hilo y muestra en pantalla dicha suma.

Me regresa datos que no corresponden (ejemplo):
Número aleatorio: 8
Número aleatorio: 7
Número aleatorio: 7
Número aleatorio: 7
Número aleatorio: 7
Suma de los números: 7

Aquí el código:
Código C:
Ver original
  1. #include <pthread.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. struct hilos_random_parms
  6. {
  7.     int randi;
  8. };
  9.  
  10. int aleatorios[5];
  11. int cont = 0;
  12.  
  13. void* hilos_random(void* parameters)
  14. {
  15.     struct hilos_random_parms* p = (struct hilos_random_parms*)parameters;
  16.     srand(time(NULL));
  17.     aleatorios[cont] = (rand() % p->randi) + 1;    
  18.     printf("Número aleatorio: %d \n", aleatorios[cont]);
  19.     cont++;
  20.     return NULL;
  21. }
  22.  
  23. int main()
  24. {
  25.     pthread_t thread1_id;
  26.     pthread_t thread2_id;
  27.     pthread_t thread3_id;
  28.     pthread_t thread4_id;
  29.     pthread_t thread5_id;
  30.    
  31.     struct hilos_random_parms thread1_args;
  32.  
  33.     thread1_args.randi = 10;   
  34.  
  35.     pthread_create(&thread1_id, NULL, &hilos_random, &thread1_args);
  36.     pthread_create(&thread2_id, NULL, &hilos_random, &thread1_args);
  37.     pthread_create(&thread3_id, NULL, &hilos_random, &thread1_args);
  38.     pthread_create(&thread4_id, NULL, &hilos_random, &thread1_args);
  39.     pthread_create(&thread5_id, NULL, &hilos_random, &thread1_args);
  40.    
  41.     pthread_join(thread1_id, NULL);
  42.     pthread_join(thread2_id, NULL);
  43.     pthread_join(thread3_id, NULL);
  44.     pthread_join(thread4_id, NULL);
  45.     pthread_join(thread5_id, NULL);
  46.    
  47.     int total = 0;
  48.     int i;
  49.     for (i = 0; i < 5; i++)
  50.     {
  51.         total += aleatorios[i];
  52.     }
  53.    
  54.     printf("Suma de los números: %d \n", total);
  55.  
  56.     return 0;
  57. }