0% found this document useful (0 votes)
8 views2 pages

Semaphores Producer Consumer

The document contains a C program that implements a producer-consumer problem using semaphores for synchronization. It defines a buffer of fixed size and creates producer and consumer threads that produce and consume items while managing access to the buffer. The program initializes semaphores, creates threads, and ensures proper synchronization to avoid race conditions.

Uploaded by

Arnav Balpande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Semaphores Producer Consumer

The document contains a C program that implements a producer-consumer problem using semaphores for synchronization. It defines a buffer of fixed size and creates producer and consumer threads that produce and consume items while managing access to the buffer. The program initializes semaphores, creates threads, and ensures proper synchronization to avoid race conditions.

Uploaded by

Arnav Balpande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0, out = 0;

Type your text

sem_t mutex, empty, full;


void *producer(void *arg)
{
int item;
for (int i = 0; i < 10; i++)
{
item = i + 1;
sem_wait(&empty);
sem_wait(&mutex);
buffer[in] = item;
printf("Produced item: %d\n", item);
in = (in + 1) % BUFFER_SIZE;
sem_post(&mutex);
sem_post(&full);
}
return NULL;
}
void *consumer(void *arg)
{
int item;
for (int i = 0; i < 10; i++)
{
sem_wait(&full);
sem_wait(&mutex);
item = buffer[out];
printf("Consumed item: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
sem_post(&mutex);
sem_post(&empty);
}
return NULL;
}
int main()
{
pthread_t tid_producer, tid_consumer;
// Initialize semaphores

sem_init(&mutex, 0, 1);
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
// Create producer and consumer threads
pthread_create(&tid_producer, NULL, producer, NULL);
pthread_create(&tid_consumer, NULL, consumer, NULL);
// Wait for threads to finish
pthread_join(tid_producer, NULL);
pthread_join(tid_consumer, NULL);
// Destroy semaphores
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy