Cse4a 25 Prac6
Cse4a 25 Prac6
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int count = 0;
sem_t empty, full;
pthread_mutex_t mutex;
sem_t readWriteLock;
int main() {
pthread_t t[5], prodThread, consThread;
int choice, knt, val;
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
while (1) {
printf("\nMENU:\n[1] Thread Demonstration\n[2] Producer-
Consumer Problem\n[3] Reader-Writer Problem (IPC)\n[4] Exit\nYour
Choice: ");
scanf("%d", &choice);
if (choice == 1) {
printf("How Many Threads: ");
scanf("%d", &knt);
if (choice == 1)
pthread_create(&t[i], NULL, add, num);
else if (choice == 2)
pthread_create(&t[i], NULL, mul, num);
else
printf("Invalid Choice\n");
pthread_join(t[i], NULL);
}
} else if (choice == 2) {
pthread_create(&prodThread, NULL, producer, NULL);
pthread_create(&consThread, NULL, consumer, NULL);
pthread_join(prodThread, NULL);
pthread_join(consThread, NULL);
} else if (choice == 3) {
int shmid = shmget(1234, sizeof(int), IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget failed");
exit(1);
}
if (fork() == 0) {
sem_wait(&readWriteLock);
*data = rand() % 100;
printf("Writer wrote data: %d\n", *data);
sem_post(&readWriteLock);
shmdt(data);
exit(0);
} else {
wait(NULL);
if (fork() == 0) {
sem_wait(&readWriteLock);
printf("Reader read data: %d\n", *data);
sem_post(&readWriteLock);
shmdt(data);
exit(0);
}
wait(NULL);
}
shmdt(data);
shmctl(shmid, IPC_RMID, NULL);
} else if (choice == 4) {
break;
} else {
printf("Invalid Choice!\n");
}
}
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
Output:
root@Anuj:nano practical6.c
root@Anuj:gcc practical6.c
root@Anuj:./a.out
MENU:
[1] Thread Demonstration
[2] Producer-Consumer Problem
[3] Reader-Writer Problem (IPC)
[4] Exit
Your Choice: 1
How Many Threads: 3
Enter Value-1: 23
[1] Addition
[2] Multiplication
Your Choice: 1
Add Num To Self: 46
Increment by 11: 57
Enter Value-2: 24
[1] Addition
[2] Multiplication
Your Choice: 2
Multiply Num By Self: 576
Multiply Product By 2: 1152
Enter Value-3: 98
[1] Addition
[2] Multiplication
Your Choice: 2
Multiply Num By Self: 9604
Multiply Product By 2: 19208
MENU:
[1] Thread Demonstration
[2] Producer-Consumer Problem
[3] Reader-Writer Problem (IPC)
[4] Exit
Your Choice: 2
Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
Produced: 6
Consumed: 6
Produced: 7
Consumed: 7
Produced: 8
Consumed: 8
Produced: 9
Consumed: 9
MENU:
[1] Thread Demonstration
[2] Producer-Consumer Problem
[3] Reader-Writer Problem (IPC)
[4] Exit
Your Choice: 3
Writer wrote data: 83
Reader read data: 83
MENU:
[1] Thread Demonstration
[2] Producer-Consumer Problem
[3] Reader-Writer Problem (IPC)
[4] Exit
Your Choice: 4