Skip to content

Instantly share code, notes, and snippets.

@shelterz
Last active August 23, 2019 09:15
Show Gist options
  • Save shelterz/e876520f9039152b699896036d470c37 to your computer and use it in GitHub Desktop.
Save shelterz/e876520f9039152b699896036d470c37 to your computer and use it in GitHub Desktop.
producer consumer problem
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
sem_t fill_count, empty_count;
pthread_mutex_t lock;
int p;
void *producer(void *param)
{
for(;;)
{
sem_wait(&empty_count);
pthread_mutex_lock(&lock);
p++;
pthread_mutex_unlock(&lock);
sem_post(&fill_count);
}
}
void *consumer(void *param)
{
for(;;)
{
sem_wait(&fill_count);
pthread_mutex_lock(&lock);
p--;
pthread_mutex_unlock(&lock);
sem_post(&empty_count);
}
}
int main(void)
{
pthread_t t[3];
sem_init(&fill_count, 0, 0);
sem_init(&empty_count, 0, BUFFER_SIZE);
pthread_mutex_init(&lock, NULL);
pthread_create(&t[0], NULL, consumer, NULL);
pthread_create(&t[1], NULL, producer, NULL);
pthread_create(&t[2], NULL, producer, NULL);
for(;;)
{
printf("p = %d\n", p);
}
pthread_cancel(t[0]);
pthread_cancel(t[1]);
pthread_cancel(t[2]);
sem_destroy(&fill_count);
sem_destroy(&empty_count);
pthread_mutex_destroy(&lock);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment