week3
week3
Aim:
Algorithm:
1. The Semaphore mutex, full & empty are initialized.
2. In the case of producer process
3. Produce an item in to temporary variable.
If there is empty space in the buffer check the mutex value for enter into
the critical section. If the mutex value is 0, allow the producer to add value
in the temporary variable to the buffer.
4. In the case of consumer process
i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the
mutex==0, remove item from buffer
iii) Signal the mutex value and reduce the empty value by 1.
iv) Consume the item.
5. Print the result
Code
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
pthread_mutex_t mutex;
sem_t empty, full;
// Producer function
void* producer(void* arg) {
int item;
for(int i = 0; i < 10; i++) { // Producing 10 items
item = i + 1; // Produce an item
// Consumer function
void* consumer(void* arg) {
int item;
for(int i = 0; i < 10; i++) { // Consuming 10 items
sem_wait(&full); // Wait for a filled slot
pthread_mutex_lock(&mutex); // Lock buffer access
int main() {
pthread_t prod, cons;
// Initialize semaphores
sem_init(&empty, 0, BUFFER_SIZE); // Buffer starts as empty
sem_init(&full, 0, 0); // No full slots initially
pthread_mutex_init(&mutex, NULL);
return 0;
}
Output: