OSEXP06
OSEXP06
6
Process Management: Synchronization
A. Write a C program to implement the solution of the Producer
consumer problem through Semaphore.
Roll No:-75
Date of Performance:06/03/2025
Date of Submission:12/03/2025
Marks:
Sign:
Objective:
Theory:
Program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
int item;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sem_post(&full);
pthread_exit(NULL);
int item;
sem_wait(&full);
pthread_mutex_lock(&mutex);
item = buffer[out];
pthread_mutex_unlock(&mutex);
sem_post(&empty);
pthread_exit(NULL);
}
CSL403: Operating System Lab
int main() {
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
//Out[put
Conclusion:
What is Semaphore?
Ans:-A semaphore is essentially a variable or abstract data type that acts as a counter.
Key Features:
● Synchronization Tool:
○ Semaphores help coordinate the actions of multiple processes, ensuring that they
access shared resources in a controlled manner.
○
CSL403: Operating System Lab
● Preventing Race Conditions:
○ They are crucial for preventing race conditions, which occur when the outcome
of a program depends on the unpredictable order in which multiple processes
execute.
○
Ans:-
● Types of Semaphores:
○ Binary Semaphore:
■ Has only two values: 0 and 1.
■
■ Often used to implement locks (also called mutexes), ensuring that only
one process can access a critical section at a time.
■
○ Counting Semaphore:
■ Can have non-negative integer values.
■ Used to control access to a resource with a limited number of instances.