0% found this document useful (0 votes)
86 views3 pages

Threads and Semaphore - Reader Writer Problem

The code implements the classical reader-writer problem using threads and semaphores. It allows multiple reader threads but only one writer thread at a time. A mutex lock tracks the number of active readers and a semaphore ensures only one writer can access the shared data at any time. The code creates reader and writer threads, each modifying or reading a shared counter, to demonstrate the reader-writer synchronization.

Uploaded by

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

Threads and Semaphore - Reader Writer Problem

The code implements the classical reader-writer problem using threads and semaphores. It allows multiple reader threads but only one writer thread at a time. A mutex lock tracks the number of active readers and a semaphore ensures only one writer can access the shared data at any time. The code creates reader and writer threads, each modifying or reading a shared counter, to demonstrate the reader-writer synchronization.

Uploaded by

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

Title: Implementation of Classical problems using Threads and

Semaphore, reader-writer problem.

Code-

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

sem_t write;
pthread_mutex_t mutex;
int cnt = 1;
int numreader = 0;

void *writer(void *wno)


{
sem_wait(&write);
cnt = cnt*2;
printf("Writer %d modified cnt to %d\n",(*((int *)wno)),cnt);
sem_post(&write);

}
void *reader(void *rno)
{
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1) {
sem_wait(&write);
}
pthread_mutex_unlock(&mutex);
printf("Reader %d- read cnt as %d\n",*((int *)rno),cnt);
pthread_mutex_lock(&mutex);
numreader--;
if(numreader == 0) {
sem_post(&write);
}
pthread_mutex_unlock(&mutex);
}

int main()
{

pthread_t read[5],writee[3];
pthread_mutex_init(&mutex, NULL);
sem_init(&write,0,1);

int a[5] = {1,2,3,4,5}; //Just used for numbering the producer and consumer

for(int i = 0; i < 5; i++) {


pthread_create(&read[i], NULL, (void *)reader, (void *)&a[i]);
}
for(int i = 0; i < 3; i++) {
pthread_create(&writee[i], NULL, (void *)writer, (void *)&a[i]);
}

for(int i = 0; i < 5; i++) {


pthread_join(read[i], NULL);
}
for(int i = 0; i < 3; i++) {
pthread_join(writee[i], NULL);
}

pthread_mutex_destroy(&mutex);
sem_destroy(&write);

return 0;

Output

You might also like