Last active
August 29, 2015 14:19
-
-
Save thiagovsk/76dc6a0ba88ccfa646fb to your computer and use it in GitHub Desktop.
This file contains 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 <pthread.h> | |
#include <stdio.h> | |
#include <semaphore.h> | |
#define MAX_ITENS 100 | |
#define USE_SEM | |
#ifdef USE_SEM | |
sem_t mutex; // protege a operação de adicionar ou remover itens | |
sem_t producer_calls_available; // verifica se há chamadas disponíves para o produtor | |
sem_t consumer_calls_available; // verifica se há chamadas disponíveis para o consumidor | |
#endif | |
unsigned int items = 0; | |
/* função crítica: produzir um item*/ | |
void produce_item() { | |
#ifdef USE_SEM | |
sem_wait(&producer_calls_available); | |
sem_wait(&mutex); | |
#endif | |
items += 1; | |
printf("P:%i\n", items); | |
#ifdef USE_SEM | |
sem_post(&mutex); | |
sem_post(&consumer_calls_available); | |
#endif | |
} | |
/* função crítica: consumir um item*/ | |
void consume_item() { | |
#ifdef USE_SEM | |
sem_wait(&consumer_calls_available); | |
sem_wait(&mutex); | |
#endif | |
items -= 1; | |
printf("C:%i\n", items); | |
#ifdef USE_SEM | |
sem_post(&mutex); | |
sem_post(&producer_calls_available); | |
#endif | |
} | |
/* função para o thread produtor */ | |
void* producer() { | |
while(1) { | |
if(items < MAX_ITENS) { | |
produce_item(); | |
} | |
} | |
} | |
/* função para o thread consumidor */ | |
void* consumer() { | |
while(1) { | |
if(items > 0) { | |
consume_item(); | |
} | |
} | |
} | |
int main() { | |
#ifdef USE_SEM | |
sem_init(&producer_calls_available, 0, MAX_ITENS); // posso produzir MAX_ITENS :) | |
sem_init(&consumer_calls_available, 0, 0); // ainda não posso consumir :( | |
sem_init(&mutex, 0, 1); | |
#endif | |
pthread_t consumer_thread, producer_thread; | |
pthread_create(&producer_thread, NULL, producer, NULL); | |
pthread_create(&consumer_thread, NULL, consumer, NULL); | |
pthread_join(producer_thread, NULL); | |
pthread_join(consumer_thread, NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment