Last active
May 12, 2016 16:46
-
-
Save RicardoLara/a3f13050b383dbcf1ac8e6d0addd6f44 to your computer and use it in GitHub Desktop.
Primer prog de Semaforos, la bse papa :v
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <sys/sem.h> | |
| #include <sys/types.h> | |
| #include <pthread.h> | |
| #include <unistd.h> | |
| #define CONSUMIDOR 0 | |
| #define PRODUCTOR 1 | |
| int s,j; | |
| // s es el Semaforo | |
| void sem_wait(int k){ | |
| struct sembuf operacion; | |
| operacion.sem_num = k; | |
| operacion.sem_op = -1; // Operacion Wait | |
| operacion.sem_flg = SEM_UNDO; | |
| semop(s,&operacion,1); | |
| return; | |
| } | |
| void sem_signal(int k){ | |
| struct sembuf operacion; | |
| operacion.sem_num = k; | |
| operacion.sem_op = 1; // Operacion Signal | |
| operacion.sem_flg = SEM_UNDO; | |
| semop(s,&operacion,1); | |
| return; | |
| } | |
| void * Productor(){ | |
| int i; | |
| for(i=0; i<10; i++){ | |
| sem_wait(PRODUCTOR); | |
| j = i; | |
| printf("Productor puso -> %d\n",j); | |
| sem_signal(CONSUMIDOR); | |
| } | |
| pthread_exit(0); | |
| } | |
| void * Consumidor(){ | |
| int i; | |
| for(i=0; i<10; i++){ | |
| sem_wait(CONSUMIDOR); | |
| printf("Consumidor lee -> %d\n",j); | |
| sem_signal(PRODUCTOR); | |
| } | |
| pthread_exit(0); | |
| } | |
| int main(){ | |
| pthread_t arr[2]; | |
| key_t llave = ftok ( "/bin/ls" , 25 ); | |
| if ( (s = semget(llave,2,IPC_CREAT|0600)) < 0 ){ | |
| printf("Error SEMGET\n"); | |
| exit(-1); | |
| } | |
| semctl(s,CONSUMIDOR,SETVAL,0); | |
| semctl(s,PRODUCTOR,SETVAL,1); | |
| if ( pthread_create( &arr[0], NULL, Productor, NULL ) < 0){ | |
| printf("Error HILOS\n"); | |
| exit(-1); | |
| } | |
| if ( pthread_create( &arr[1], NULL, Consumidor, NULL ) < 0){ | |
| printf("Error HILOS\n"); | |
| exit(-1); | |
| } | |
| pthread_join (arr[0], NULL); | |
| pthread_join (arr[1], NULL); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment