READER WRITER SEMAPHORE
// READER WRITER SEMAPHORE
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
int shared_data = 0;
int read_count = 0;
sem_t wrt;
pthread_mutex_t mutex;
void *writer(void *writer_id) {
int id = *(int *)writer_id;
sem_wait(&wrt);
shared_data += 1;
printf("Writer %d
modified shared_data to %d\n", id, shared_data);
sem_post(&wrt);
return NULL; }
void *reader(void
*reader_id) {
int id = *(int *)reader_id;
pthread_mutex_lock(&mutex);
read_count++;
if (read_count == 1)
sem_wait(&wrt);
pthread_mutex_unlock(&mutex);
printf("Reader %d: read shared_data as %d\n", id,
shared_data);
pthread_mutex_lock(&mutex);
read_count--;
if (read_count == 0)
sem_post(&wrt);
pthread_mutex_unlock(&mutex);
return NULL; }
int main() {
pthread_t read[5], write[3];
int reader_ids[5] = {1, 2, 3, 4, 5};
int writer_ids[3] = {1, 2, 3};
sem_init(&wrt, 0, 1);
pthread_mutex_init(&mutex, NULL);
for (int i = 0; i < 3; i++) {
pthread_create(&write[i], NULL, writer, (void
*)&writer_ids[i]); }
for (int i = 0; i < 5; i++) {
pthread_create(&read[i], NULL, reader, (void
*)&reader_ids[i]); }
for (int i = 0; i < 3; i++) {
pthread_join(write[i], NULL); }
for (int i = 0; i < 5; i++) {
pthread_join(read[i], NULL); }
sem_destroy(&wrt);
pthread_mutex_destroy(&mutex);
return 0;
}
Comments
Post a Comment