Advertisement
Guest User

Untitled

a guest
Oct 21st, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 KB | None | 0 0
  1. /*
  2.  ABAC...20 veces
  3.  1. mutex, 2. posix.
  4. */
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. #include <pthread.h>
  11.  
  12.  
  13. void* rutinaA(void*);
  14. void* rutinaB(void*);
  15. void* rutinaC(void*);
  16.  
  17. pthread_mutex_t mA = PTHREAD_MUTEX_INITIALIZER;
  18. pthread_mutex_t mB = PTHREAD_MUTEX_INITIALIZER;
  19. pthread_mutex_t mC = PTHREAD_MUTEX_INITIALIZER;
  20. pthread_mutex_t swap = PTHREAD_MUTEX_INITIALIZER;
  21.  
  22. int contador=20;
  23. int main(int argc, char* argv[]){
  24.   pthread_t hiloA;
  25.   pthread_t hiloB;
  26.   pthread_t hiloC;
  27.   // seteo en 0 a mC y SWAP.
  28.   pthread_mutex_lock(&mC);
  29.   pthread_mutex_lock(&swap);
  30.   // asocio hilos a su rutina
  31.   pthread_create(&hiloA,NULL,rutinaA,NULL);
  32.   pthread_create(&hiloB,NULL,rutinaB,NULL);
  33.   pthread_create(&hiloC,NULL,rutinaC,NULL);
  34.   // espero threads
  35.   pthread_join(hiloA,NULL);
  36.   pthread_join(hiloB,NULL);
  37.   pthread_join(hiloC,NULL);
  38.   printf("Han Finalizado los tres hilos.\n");
  39. }
  40.  
  41. void* rutinaA(void* x){
  42.   while(contador < 20){
  43.     pthread_mutex_lock(&mA);
  44.     printf("A");
  45.     pthread_mutex_unlock(&swap);
  46.     contador++;
  47.   }
  48.   pthread_exit(0);
  49. }
  50. void* rutinaB(void* x){
  51.   while(contador < 20){
  52.     pthread_mutex_lock(&mB);
  53.     pthread_mutex_lock(&swap);
  54.     printf("B");
  55.     pthread_mutex_unlock(&mA);
  56.     pthread_mutex_unlock(&mC);
  57.     contador++;
  58.   }
  59.   pthread_exit(0);
  60. }
  61.  
  62. void* rutinaC(void* x){
  63.   while(contador < 20){
  64.     pthread_mutex_lock(&mC);
  65.     pthread_mutex_lock(&swap);
  66.     printf("B");
  67.     pthread_mutex_unlock(&mA);
  68.     pthread_mutex_unlock(&mB);
  69.     contador++;
  70.   }
  71.   pthread_exit(0);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement