Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ABAC...20 veces
- 1. mutex, 2. posix.
- */
- #include <string.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <pthread.h>
- void* rutinaA(void*);
- void* rutinaB(void*);
- void* rutinaC(void*);
- pthread_mutex_t mA = PTHREAD_MUTEX_INITIALIZER;
- pthread_mutex_t mB = PTHREAD_MUTEX_INITIALIZER;
- pthread_mutex_t mC = PTHREAD_MUTEX_INITIALIZER;
- pthread_mutex_t swap = PTHREAD_MUTEX_INITIALIZER;
- int contador=20;
- int main(int argc, char* argv[]){
- pthread_t hiloA;
- pthread_t hiloB;
- pthread_t hiloC;
- // seteo en 0 a mC y SWAP.
- pthread_mutex_lock(&mC);
- pthread_mutex_lock(&swap);
- // asocio hilos a su rutina
- pthread_create(&hiloA,NULL,rutinaA,NULL);
- pthread_create(&hiloB,NULL,rutinaB,NULL);
- pthread_create(&hiloC,NULL,rutinaC,NULL);
- // espero threads
- pthread_join(hiloA,NULL);
- pthread_join(hiloB,NULL);
- pthread_join(hiloC,NULL);
- printf("Han Finalizado los tres hilos.\n");
- }
- void* rutinaA(void* x){
- while(contador < 20){
- pthread_mutex_lock(&mA);
- printf("A");
- pthread_mutex_unlock(&swap);
- contador++;
- }
- pthread_exit(0);
- }
- void* rutinaB(void* x){
- while(contador < 20){
- pthread_mutex_lock(&mB);
- pthread_mutex_lock(&swap);
- printf("B");
- pthread_mutex_unlock(&mA);
- pthread_mutex_unlock(&mC);
- contador++;
- }
- pthread_exit(0);
- }
- void* rutinaC(void* x){
- while(contador < 20){
- pthread_mutex_lock(&mC);
- pthread_mutex_lock(&swap);
- printf("B");
- pthread_mutex_unlock(&mA);
- pthread_mutex_unlock(&mB);
- contador++;
- }
- pthread_exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement