About
bounded buffer
include <stdio.h>
include <stdlib.h>
include <pthread.h>
include <semaphore.h>
define BUFFER_SIZE 5
define NUM_PRODUCERS 2
define NUM_CONSUMERS 3
int buffer[BUFFER_SIZE]; int in = 0; int out = 0;
sem_t emptySlots; // initially equal to number of slots allocated in the buffer sem_t fullSlots; // initially equal to 0 sem_t mutex; // binary semaphore initially zero
void producer(void arg) { int producerId = (int )arg; int item;
while (1) {
item = rand() % 100; // Generate a random item to produce
sem_wait(&emptySlots); // Wait for an empty slot in the buffer
sem_wait(&mutex); // Acquire the mutex to access the buffer
// Add the item to the buffer
buffer[in] = item;
printf("Producer %d produced item: %d\n", producerId, item);
in = (in + 1) % BUFFER_SIZE;
sem_post(&mutex); // Release the mutex
sem_post(&fullSlots); // Signal that a slot is filled
sleep(rand() % 3); // Sleep for a random time
}
pthread_exit(NULL);
}
void consumer(void arg) { int consumerId = (int )arg; int item;
while (1) {
sem_wait(&fullSlots); // Wait for a filled slot in the buffer
sem_wait(&mutex); // Acquire the mutex to access the buffer
// Remove an item from the buffer
item = buffer[out];
printf("Consumer %d consumed item: %d\n", consumerId, item);
out = (out + 1) % BUFFER_SIZE;
sem_post(&mutex); // Release the mutex
sem_post(&emptySlots); // Signal that a slot is empty
sleep(rand() % 3); // Sleep for a random time
}
pthread_exit(NULL);
}
int main() { pthread_t producerThreads[NUM_PRODUCERS];// initializing the producer threads pthread_t consumerThreads[NUM_CONSUMERS];// initializing the consumer threads int producerIds[NUM_PRODUCERS]; int consumerIds[NUM_CONSUMERS];
srand(time(NULL));
sem_init(&emptySlots, 0, BUFFER_SIZE); // Initialize the empty slots semaphore
sem_init(&fullSlots, 0, 0); // Initialize the full slots semaphore
sem_init(&mutex, 0, 1); // Initialize the mutex semaphore
for (int i = 0; i < NUM_PRODUCERS; i++) {
producerIds[i] = i + 1;
pthread_create(&producerThreads[i], NULL, producer, (void *)&producerIds[i]);// creating the producer threads
}
for (int i = 0; i < NUM_CONSUMERS; i++) {
consumerIds[i] = i + 1;
pthread_create(&consumerThreads[i], NULL, consumer, (void *)&consumerIds[i]);// creating the consumer threads
}
// Wait for the threads to finish
for (int i = 0; i < NUM_PRODUCERS; i++) {
pthread_join(producerThreads[i], NULL);
}
for (int i = 0; i < NUM_CONSUMERS; i++) {
pthread_join(consumerThreads[i], NULL);
}
sem_destroy(&emptySlots);
sem_destroy(&fullSlots);
sem_destroy(&mutex);
return 0;
} bounded buffer
sleeping barber
include <stdio.h>
include <stdlib.h>
include <pthread.h>
include <semaphore.h>
include <unistd.h>
define NUM_CUSTOMERS 10
define NUM_CHAIRS 5
// there are a few scenarios in this problem: // 1.if the customer comes to shop and sees the barber is busy he goes to the waiting room,if the waiting room is full then he leaves // 2.Barber has one chair to cut the hair of thje customer.When the barber is done with the customer then he will cut the hair of the next customer //from the waiting room // 3.If there is no customer in the waiting room the barber will sleep // 4. So in this problem we have a total of 3 semaphores
sem_t barberReady;// used by both barber and customers initial value is zero . so initally barber is sleeping sem_t customerReady;// if there is no customer in the waiting room the barber will sleep initial value is zero. so initially there is no customer sem_t accessSeats;// it is used to access the numFreeSeats variable initial value is one int numFreeSeats = NUM_CHAIRS; // it is the number of seats available in the waiting room and only one customer can access the variable at a time
void barber(void arg) { while (1) { // Barber waits for a customer to arrive sem_wait(&customerReady);
// Barber acquires access to the seats
sem_wait(&accessSeats);
// Barber increments the number of free seats
numFreeSeats++;
// Barber signals availability to the customer
sem_post(&barberReady);
// Barber releases access to the seats
sem_post(&accessSeats);
// Barber cuts hair (non-critical work)
printf("Barber is cutting hair\n");
sleep(rand() % 3);
}
}
void customer(void arg) { int customerId = (int )arg;
// Customer acquires access to the seats
sem_wait(&accessSeats);// acquires the semaphore access seats
if (numFreeSeats > 0) {
// Customer occupies a seat
numFreeSeats--;
// Customer signals readiness to the barber
sem_post(&customerReady);// increments the value of semaphore by 1 so we signal that the customer is ready
// Customer releases access to the seats
sem_post(&accessSeats); // releases the semaphore access seats
// Customer waits for the barber to be ready
sem_wait(&barberReady);
// Customer gets a haircut (non-critical work)
printf("Customer %d is getting a haircut\n", customerId);
sleep(rand() % 3);
} else {
// No free seats, customer leaves the shop
// Customer releases access to the seats
sem_post(&accessSeats);
printf("Customer %d left the shop (no available seats)\n", customerId);
}
}
int main() { pthread_t barberThread, customerThreads[NUM_CUSTOMERS]; int customerIds[NUM_CUSTOMERS];
srand(time(NULL));
sem_init(&barberReady, 0, 0);
sem_init(&customerReady, 0, 0);
sem_init(&accessSeats, 0, 1);
pthread_create(&barberThread, NULL, barber, NULL);
for (int i = 0; i < NUM_CUSTOMERS; i++) {
customerIds[i] = i + 1;
pthread_create(&customerThreads[i], NULL, customer, (void *)&customerIds[i]);
sleep(rand() % 2);
}
for (int i = 0; i < NUM_CUSTOMERS; i++) {
pthread_join(customerThreads[i], NULL);
}
// Cancel the barber thread after all customers are served
pthread_cancel(barberThread);
pthread_join(barberThread, NULL);
return 0;
}
reader-writer problem
include <stdio.h>
include <stdlib.h>
include <pthread.h>
include <semaphore.h>
include <unistd.h>
// let us try out reader - writer
define Num_Readers 5
define Num_Writers 2
sem_t mutex; // not very useful sem_t resource; // it is shared between both reader and writer sem_t readcount; // it changes the value of readcount . it is shared between readers int readcounter=0; //integer counter
void reader(void args){ int readerID = (int )args;// it typecasts void to int and then takes the value from that pointer and stores it in reader ID
while(1){
sem_wait(&readcount);// this is to indicate that the semaphore readcount has been captured to modify the value of the integer readcount variable
readcounter++; // increment the readcount counter
if(readcounter==1){
sem_wait(&resource);// this is to indicate that the semaphore resource is now taken by a reader to read the data
}
sem_post(&readcount);// this is to indicate that the semaphore readcount has been released so that other readers can enter
printf("Reader %d is reading\n",readerID);
sem_wait(&readcount); // the semaphore is acquired again so that it can modify the value of the readcount
readcounter--;
if(readcounter==0){
// no readers are present so writers can enter
sem_post(&resource);
}
sem_post(&readcount);
// reader prints non critical information
printf("Reader %d has finished reading\n",readerID);
}
} void writer(void args){ int writerID=(int )args;// it typecasts void to int and then takes the value from that pointer and stores it in writerID
while(1){
sem_wait(&mutex);
sem_wait(&resource);// capture the semaphore resource to ensure that other writers or readers cannot enter while one is writing
printf("Writer %d is now writing\n",writerID);
sem_post(&resource);// release the semaphore
sem_post(&mutex);
printf("Writer %d has finished\n",writerID);
}
}
int main(){ pthread_t reader_threads[Num_Readers],writer_threads[Num_Writers]; int readersID[Num_Readers],writersID[Num_Writers];
sem_init(&mutex,0,1); // int sem_init(sem_t *sem, int pshared, unsigned int value);
sem_init(&resource,0,1);
sem_init(&readcount,0,1);
for(int i=0;i<Num_Readers;i++){
readersID[i]=i+1;
pthread_create(&reader_threads[i],NULL,reader,(void *)&readersID[i]); //pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine)(void *), void *arg);
}
for(int i=0;i<Num_Writers;i++){
writersID[i]=i+1;
pthread_create(&writer_threads[i],NULL, writer, (void *)&writersID[i]);
}
for(int i=0;i<Num_Readers;i++){
pthread_join(reader_threads[i],NULL);
}
for(int i=0;i<Num_Writers;i++){
pthread_join(writer_threads[i],NULL);
}
return 0;
}