Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

OS LAB 8 4th Semester

CIS – 302 – Operating System (OS)


Fatima Qaiser
Fall 2024
LAB 8
OS LAB 8 4th Semester

Activities:
1. Develop a solution program for a Dining-Philosopher problem.
1. //dining_philosophers.c
2. #include <pthread.h>
3. #include <semaphore.h>
4. #include <stdio.h>
5.
6. #define N 5
7. #define THINKING 2
8. #define HUNGRY 1
9. #define EATING 0
10. #define LEFT (phnum + 4) % N
11. #define RIGHT (phnum + 1) % N
12.
13. int state[N];
14. int phil[N] = { 0, 1, 2, 3, 4 };
15.
16. sem_t mutex;
17. sem_t S[N];
18.
19. void test(int phnum)
20. {
21. if (state[phnum] == HUNGRY
22. && state[LEFT] != EATING
23. && state[RIGHT] != EATING) {
24. // state that eating
25. state[phnum] = EATING;
26.
27. sleep(2);
28.
29. printf("Philosopher %d takes fork %d and %d\n",
30. phnum + 1, LEFT + 1, phnum + 1);
31.
32. printf("Philosopher %d is Eating\n", phnum + 1);
33.
34. // sem_post(&S[phnum]) has no effect
35. // during takefork
36. // used to wake up hungry philosophers
37. // during putfork
38. sem_post(&S[phnum]);
39. }
40. }
41.
42. // take up chopsticks
43. void take_fork(int phnum)
44. {
45.
46. sem_wait(&mutex);
47.
48. // state that hungry
49. state[phnum] = HUNGRY;
50.
51. printf("Philosopher %d is Hungry\n", phnum + 1);
OS LAB 8 4th Semester

52.
53. // eat if neighbours are not eating
54. test(phnum);
55.
56. sem_post(&mutex);
57.
58. // if unable to eat wait to be signalled
59. sem_wait(&S[phnum]);
60.
61. sleep(1);
62. }
63.
64. // put down chopsticks
65. void put_fork(int phnum)
66. {
67.
68. sem_wait(&mutex);
69.
70. // state that thinking
71. state[phnum] = THINKING;
72.
73. printf("Philosopher %d putting fork %d and %d down\n",
74. phnum + 1, LEFT + 1, phnum + 1);
75. printf("Philosopher %d is thinking\n", phnum + 1);
76.
77. test(LEFT);
78. test(RIGHT);
79.
80. sem_post(&mutex);
81. }
82.
83. void* philosopher(void* num)
84. {
85.
86. while (1) {
87.
88. int* i = num;
89.
90. sleep(1);
91.
92. take_fork(*i);
93.
94. sleep(0);
95.
96. put_fork(*i);
97. }
98. }
99.
100. int main()
101. {
102.
103. int i;
104. pthread_t thread_id[N];
105.
106. // initialize the semaphores
107. sem_init(&mutex, 0, 1);
108.
109. for (i = 0; i < N; i++)
110.
OS LAB 8 4th Semester

111. sem_init(&S[i], 0, 0);


112.
113. for (i = 0; i < N; i++) {
114.
115. // create philosopher processes
116. pthread_create(&thread_id[i], NULL,
117. philosopher, &phil[i]);
118.
119. printf("Philosopher %d is thinking\n", i + 1);
120. }
121.
122. for (i = 0; i < N; i++)
123.
124. pthread_join(thread_id[i], NULL);
125. }
126.

2. Develop a solution program for a Producer-Consumer problem.


1. //producer_consumer.c
2. #include <stdio.h>
3. #include <stdlib.h>
4.
5. // Initialize a mutex to 1
6. int mutex = 1;
7.
8. // Number of full slots as 0
9. int full = 0;
10.
11. // Number of empty slots as size
12. // of buffer
OS LAB 8 4th Semester

13. int empty = 10, x = 0;


14.
15. // Function to produce an item and
16. // add it to the buffer
17. void producer()
18. {
19. // Decrease mutex value by 1
20. --mutex;
21.
22. // Increase the number of full
23. // slots by 1
24. ++full;
25.
26. // Decrease the number of empty
27. // slots by 1
28. --empty;
29.
30. // Item produced
31. x++;
32. printf("\nProducer produces"
33. "item %d",
34. x);
35.
36. // Increase mutex value by 1
37. ++mutex;
38. }
39.
40. // Function to consume an item and
41. // remove it from buffer
42. void consumer()
43. {
44. // Decrease mutex value by 1
45. --mutex;
46.
47. // Decrease the number of full
48. // slots by 1
49. --full;
50.
51. // Increase the number of empty
52. // slots by 1
53. ++empty;
54. printf("\nConsumer consumes "
55. "item %d",
56. x);
57. x--;
58.
59. // Increase mutex value by 1
60. ++mutex;
61. }
62.
63. // Driver Code
64. int main()
65. {
66. int n, i;
67. printf("\n1. Press 1 for Producer"
68. "\n2. Press 2 for Consumer"
69. "\n3. Press 3 for Exit");
70.
71. // Using '#pragma omp parallel for'
OS LAB 8 4th Semester

72. // can give wrong value due to


73. // synchronization issues.
74.
75. // 'critical' specifies that code is
76. // executed by only one thread at a
77. // time i.e., only one thread enters
78. // the critical section at a given time
79. #pragma omp critical
80.
81. for (i = 1; i > 0; i++) {
82.
83. printf("\nEnter your choice:");
84. scanf("%d", &n);
85.
86. // Switch Cases
87. switch (n) {
88. case 1:
89.
90. // If mutex is 1 and empty
91. // is non-zero, then it is
92. // possible to produce
93. if ((mutex == 1)
94. && (empty != 0)) {
95. producer();
96. }
97.
98. // Otherwise, print buffer
99. // is full
100. else {
101. printf("Buffer is full!");
102. }
103. break;
104.
105. case 2:
106.
107. // If mutex is 1 and full
108. // is non-zero, then it is
109. // possible to consume
110. if ((mutex == 1)
111. && (full != 0)) {
112. consumer();
113. }
114.
115. // Otherwise, print Buffer
116. // is empty
117. else {
118. printf("Buffer is empty!");
119. }
120. break;
121.
122. // Exit Condition
123. case 3:
124. exit(0);
125. break;
126. }
127. }
128. }
129.
OS LAB 8 4th Semester
OS LAB 8 4th Semester

3. Develop a C programming code for sleeping barber problem. Barber


will take 20 seconds for a haircut. Barber shop has 3 seats in the
waiting area.
1. //sleepin_barber.c
2. #include <pthread.h>
3. #include <stdio.h>
4. #include <stdlib.h>
5. #include <unistd.h>
6. #include <semaphore.h>
7. #include <time.h>
8. #include <sys/types.h>
9. #include <sys/time.h>
10.
11. void *barber_function(void *idp);
12. void *customer_function(void *idp);
13. void serve_customer();
14. void *make_customer_function();
15.
16. /* Mutex */
17. pthread_mutex_t srvCust;
18.
19. /* Semaphores */
20. sem_t barber_ready;
21. sem_t customer_ready;
22. sem_t modifySeats;
23.
24. /* Inputs */
25. int chair_cnt;
26. int total_custs;
27.
28. int available_seats;
29. int no_served_custs = 0;
30. time_t waiting_time_sum;
31.
32. void *barber_function(void *idp)
33. {
34. int counter = 0;
35.
36. while (1)
37. {
38. /* Lock semaphore "customer_ready" - try to get a customer or sleep if there is none */
39. sem_wait(&customer_ready);
40.
41. /* Lock semaphore "modifySeats" - try to get access to seats */
42. sem_wait(&modifySeats);
43.
44. /* Increment by 1 the available seats */
45. available_seats++;
46.
47. /* Unlock semaphore "modifySeats" */
48. sem_post(&modifySeats);
49.
50. /* Unlock semaphore "barber_ready" - set barber ready to serve */
51. sem_post(&barber_ready);
OS LAB 8 4th Semester

52.
53. /* Lock mutex "srvCust" - protect service by the same barber from other threads */
54. pthread_mutex_lock(&srvCust);
55.
56. /* Serve customer */
57. serve_customer();
58.
59. /* Unlock mutex "srvCust" - finished service */
60. pthread_mutex_unlock(&srvCust);
61.
62. printf("Customer was served.\n");
63.
64. counter++;
65. if (counter == (total_custs - no_served_custs))
66. break;
67. }
68. pthread_exit(NULL);
69. }
70.
71. void *customer_function(void *idp)
72. {
73. struct timeval start, stop;
74.
75. /* Lock semaphore "modifySeats" */
76. sem_wait(&modifySeats);
77.
78. /* If there is available seat */
79. if (available_seats >= 1)
80. {
81. /* Occupy a seat */
82. available_seats--;
83.
84. printf("Customer[pid = %lu] is waiting.\n", pthread_self());
85. printf("Available seats: %d\n", available_seats);
86.
87. /* Start waiting-time counter */
88. gettimeofday(&start, NULL);
89.
90. /* Unlock semaphore "customer_ready" - set the customer ready to be served */
91. sem_post(&customer_ready);
92.
93. /* Unlock semaphore "modifySeats" */
94. sem_post(&modifySeats);
95.
96. /* Lock semaphore "barber_ready" - wait for barber to get ready */
97. sem_wait(&barber_ready);
98.
99. /* Stop waiting-time counter */
100. gettimeofday(&stop, NULL);
101.
102. double sec = (double)(stop.tv_usec - start.tv_usec) / 1000000 + (double)(stop.tv_sec -
start.tv_sec);
103.
104. /* Assign the time spent to global variable (ms) */
105. waiting_time_sum += 1000 * sec;
106. printf("Customer[pid = %lu] is being served. \n", pthread_self());
107. }
108. else
109. {
OS LAB 8 4th Semester

110. /* Unlock semaphore "modifySeats" */


111. sem_post(&modifySeats);
112. no_served_custs++;
113. printf("A Customer left.\n");
114. }
115.
116. pthread_exit(NULL);
117. }
118.
119. void serve_customer() {
120. /* Random number between 0 and 400 (miliseconds) */
121. int s = rand() % 401;
122.
123. /* Convert miliseconds to microseconds */
124. s = s * 1000;
125. usleep(s);
126. }
127.
128. void *make_customer_function() {
129. int tmp;
130. int counter = 0;
131.
132. while (counter < total_custs)
133. {
134. /* Declare and create a customer thread */
135. pthread_t customer_thread;
136.
137. tmp = pthread_create(&customer_thread, NULL, (void *)customer_function, NULL);
138.
139. if (tmp)
140. printf("Failed to create thread.");
141.
142. /* Increment the counter */
143. counter++;
144.
145. /* Sleep for 100ms before creating another customer */
146. usleep(100000);
147. }
148. }
149.
150. int main() {
151. /* Initialization, should only be called once */
152. srand(time(NULL));
153.
154. /* Barber 1 thread */
155. pthread_t barber_1;
156.
157. /* Thread that creates customers */
158. pthread_t customer_maker;
159.
160. int tmp;
161.
162. /* Initialize mutex */
163. pthread_mutex_init(&srvCust, NULL);
164.
165. /* Initialize semaphores */
166. sem_init(&customer_ready, 0, 0);
167. sem_init(&barber_ready, 0, 0);
168. sem_init(&modifySeats, 0, 1);
OS LAB 8 4th Semester

169.
170. printf("Please enter the number of seats: \n");
171. scanf("%d", &chair_cnt);
172.
173. printf("Please enter the total customers: \n");
174. scanf("%d", &total_custs);
175.
176. available_seats = chair_cnt;
177.
178. /* Create barber thread */
179. tmp = pthread_create(&barber_1, NULL, (void *)barber_function, NULL);
180.
181. if (tmp)
182. printf("Failed to create thread.");
183.
184. /* Create customer_maker thread */
185. tmp = pthread_create(&customer_maker, NULL, (void *)make_customer_function, NULL);
186.
187. if (tmp)
188. printf("Failed to create thread.");
189.
190. /* Wait for threads to finish */
191. pthread_join(barber_1, NULL);
192. pthread_join(customer_maker, NULL);
193.
194. printf("\n------------------------------------------------\n");
195. printf("Average customers' waiting time: %f ms.\n", (waiting_time_sum / (double) (total_custs -
no_served_custs)));
196. printf("Number of customers that were forced to leave: %d\n", no_served_custs);
197. }
198.
OS LAB 8 4th Semester

4. Implementation of the following Reader-Writer Problem


synchronization problems using Pthreads. ● Number of readers
allowed at a time should be equal to last two digits of your roll
number Write your first name at the end of the text file in writing
mode
OS LAB 8 4th Semester

1. //reader_writer.c
2. #include <stdio.h>
3. #include <stdlib.h>
4. #include <pthread.h>
5.
6. #define MAX_READERS 16 //lasttwo didts of rollno
7.
8. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
9. pthread_cond_t read_phase = PTHREAD_COND_INITIALIZER;
10. pthread_cond_t write_phase = PTHREAD_COND_INITIALIZER;
11.
12. int readers_count = 0;
13.
14. void *reader(void *arg) {
15. int id = *(int*)arg;
16. FILE *file = fopen("example.txt", "r");
17.
18. if (file == NULL) {
19. perror("Failed to open file");
20. exit(EXIT_FAILURE);
21. }
22.
23. // Reader enters critical section
24. pthread_mutex_lock(&mutex);
25. while (readers_count == MAX_READERS) {
26. pthread_cond_wait(&read_phase, &mutex);
27. }
28. readers_count++;
29. pthread_mutex_unlock(&mutex);
30.
31. // Reading the file
32. printf("Reader %d is reading...\n", id);
33. char buffer[1024]; // Buffer to hold the read content
34. while (fgets(buffer, sizeof(buffer), file) != NULL) {
35. printf("Reader %d read: %s", id, buffer);
36. }
37.
38. // Exiting critical section
39. pthread_mutex_lock(&mutex);
40. readers_count--;
41. if (readers_count == 0) {
42. pthread_cond_signal(&write_phase);
43. }
44. pthread_mutex_unlock(&mutex);
45.
46. fclose(file);
47. pthread_exit(NULL);
48. }
49.
50.
51. void *writer(void *arg) {
52. FILE *file = fopen("example.txt", "a");
53.
54. if (file == NULL) {
55. perror("Failed to open file");
56. exit(EXIT_FAILURE);
57. }
58.
OS LAB 8 4th Semester

59. // Writer enters critical section


60. pthread_mutex_lock(&mutex);
61. while (readers_count > 0) {
62. pthread_cond_wait(&write_phase, &mutex);
63. }
64.
65. // Writing to the file
66. printf("Writer is writing...\n");
67. fprintf(file, "Fatima\n");
68.
69. // Exiting critical section
70. pthread_mutex_unlock(&mutex);
71. pthread_cond_broadcast(&read_phase); // Wake up waiting readers
72.
73. fclose(file);
74. pthread_exit(NULL);
75. }
76.
77. int main() {
78. pthread_t readers[MAX_READERS];
79. pthread_t writer_thread;
80. int reader_ids[MAX_READERS];
81.
82. // Create reader threads
83. for (int i = 0; i < MAX_READERS; i++) {
84. reader_ids[i] = i + 1;
85. pthread_create(&readers[i], NULL, reader, &reader_ids[i]);
86. }
87.
88. // Create writer thread
89. pthread_create(&writer_thread, NULL, writer, NULL);
90.
91. // Join reader threads
92. for (int i = 0; i < MAX_READERS; i++) {
93. pthread_join(readers[i], NULL);
94. }
95.
96. // Join writer thread
97. pthread_join(writer_thread, NULL);
98.
99. return 0;
100. }
101.
OS LAB 8 4th Semester
OS LAB 8 4th Semester
OS LAB 8 4th Semester

You might also like