Experiment 4 Assignment CN
Experiment 4 Assignment CN
URN: 2023-B-15072004A
Semester: 4th
Program: BCA
resource is a bounded buffer, and multiple producers and consumers are accessing it
concurrently.
● C Programming
● Multithreading
● Mutex Locks
● Synchronization Primitives
● Producer-Consumer Problem
concepts, and synchronization primitives, including mutex locks, semaphores, and condition
Description:
● Write a C program that uses mutex locks to synchronize access to the shared buffer.
Implement a solution ensuring mutual exclusion to prevent race conditions during buffer
access.
● Extend the program to use condition variables for synchronization. Implement a solution
where condition variables signal the availability of items in the buffer and wake up
waiting threads.
Ans:-
This program creates multiple producer and consumer threads that access a shared bounded
buffer.
Code Implementation
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
// Shared buffer
int buffer[BUFFER_SIZE];
pthread_mutex_t mutex;
// Function prototypes
int main() {
pthread_mutex_init(&mutex, NULL);
thread_ids[i] = i + 1;
thread_ids[i] = i + 1;
}
// Wait for all threads to finish
pthread_join(producer_threads[i], NULL);
pthread_join(consumer_threads[i], NULL);
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
// Producer function
return NULL;
// Consumer function
return NULL;
Program Explanation
1. Shared Buffer:
o A circular buffer (buffer[]) is used, with in and out pointers to track where
producers write and consumers read.
2. Mutex:
o Used to enforce mutual exclusion during critical sections (buffer access).
3. Semaphores:
o empty: Tracks the number of empty slots in the buffer.
o full: Tracks the number of filled slots in the buffer.
o These semaphores coordinate producers and consumers, ensuring synchronization.
4. Producer:
o Waits for an empty slot (sem_wait(&empty)), locks the buffer, writes to it, unlocks
the buffer, and signals a filled slot (sem_post(&full)).
5. Consumer:
o Waits for a filled slot (sem_wait(&full)), locks the buffer, reads from it, unlocks
the buffer, and signals an empty slot (sem_post(&empty)).
6. Thread Synchronization:
o pthread_create() is used to create threads.
o pthread_join() ensures all threads complete before the program exits.
7. Simulation:
o Random delays simulate real-world production and consumption times.
Expected Output
** Producer-Consumer Problem **
...
1. Race Conditions:
o Without synchronization primitives (pthread_mutex, sem_wait, sem_post),
race conditions will cause undefined behavior.
2. Deadlocks:
o Ensure proper locking/unlocking to avoid deadlocks.
3. Buffer Overflow/Underflow:
o sem_wait() ensures producers don’t overwrite a full buffer, and consumers
don’t consume from an empty buffer.