Ver Mensaje Individual
  #2 (permalink)  
Antiguo 18/11/2009, 18:48
nevergame
 
Fecha de Ingreso: julio-2006
Ubicación: sevilla
Mensajes: 251
Antigüedad: 18 años, 7 meses
Puntos: 5
Respuesta: Ayuda con Comando C + Linux

Veamos creo que ese algoritmo es el que se denomina productor-consumidor, en el cual un proceso genera datos y otro los consume, te paso el ejemplo base y de hay deberias poder sacarlo.

Código c:
Ver original
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <errno.h>
  4. #include <semaphore.h>
  5. #include <pthread.h>
  6. #define TAMBUF 8         // Tamaño del búfer circular
  7. #define NUMDATOS 100 // Número de datos a enviar
  8. //
  9. // El buffer circular y los correspondientes punteros
  10. int buffer[TAMBUF];
  11. int bufin = 0;
  12. int bufout = 0;
  13. //
  14. // Semaforo binario
  15. pthread_mutex_t buffer_lock = PTHREAD_MUTEX_INITIALIZER;
  16. //
  17. // Variable suma
  18. unsigned long sum = 0;
  19. //
  20. // Semaforos generales
  21. sem_t hay_datos;
  22. sem_t hay_sitio;
  23. //
  24. // Funciones de escritura y lectura del buffer circular
  25. void obten_dato(int *itemp)
  26. {
  27.   *itemp = buffer[bufout];
  28.   bufout = (bufout + 1) &#37; TAMBUF;
  29.  
  30.   return;
  31. }
  32. void pon_dato(int item)
  33. {
  34.   buffer[bufin] = item;
  35.   bufin = (bufin + 1) % TAMBUF;
  36.   return;
  37. }
  38. //
  39. // Funciones productor-consumidor
  40. void *productor(void *arg1)
  41. {
  42.   int i;
  43.   for (i = 1; i <= NUMDATOS; i++) {
  44.     sem_wait(&hay_sitio);
  45.     pthread_mutex_lock(&buffer_lock);
  46.     pon_dato(i*i);
  47.     pthread_mutex_unlock(&buffer_lock);
  48.     sem_post(&hay_datos);
  49.   }
  50.   pthread_exit( NULL );
  51. }
  52. void *consumidor(void *arg2)
  53. {
  54.   int i, midato;
  55.   for (i = 1; i<= NUMDATOS; i++) {
  56.     sem_wait(&hay_datos);
  57.     pthread_mutex_lock(&buffer_lock);
  58.     obten_dato(&midato);
  59.     pthread_mutex_unlock(&buffer_lock);
  60.     sem_post(&hay_sitio);
  61.     sum += midato;
  62.   }
  63.   pthread_exit( NULL );
  64. }
  65. //
  66. // Funcion principal
  67. main()
  68. {
  69.   pthread_t tidprod, tidcons;
  70.   unsigned long i, total;
  71.   total = 0;
  72.   for (i = 1; i <= NUMDATOS; i++)
  73.     total += i*i;
  74.  
  75.   printf("El resultado deberia ser %u\n", total);
  76. //
  77. // Inicializacion de semaforos
  78.   sem_init(&hay_datos, 0, 0);
  79.   sem_init(&hay_sitio, 0, TAMBUF);
  80. //
  81. // Se crean los threads
  82.   pthread_create(&tidprod, NULL, productor, NULL);
  83.   pthread_create(&tidcons, NULL, consumidor, NULL);
  84. //
  85. // Se espera a que los threads terminen
  86.   pthread_join(tidprod, NULL);
  87.   pthread_join(tidcons, NULL);
  88.   printf("Los threads produjeron el valor %u\n", sum);
  89. }