-
Notifications
You must be signed in to change notification settings - Fork 0
/
DiningPhilosopher.c
92 lines (76 loc) · 2.44 KB
/
DiningPhilosopher.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h> // Added for sleep function
#define NUM_PHILOSOPHERS 5
#define NUM_CHOPSTICKS 5
void dine(void *ptr);
pthread_t philosopher[NUM_PHILOSOPHERS];
pthread_mutex_t chopstick[NUM_CHOPSTICKS];
int main()
{
// Define counter var i and status_message
int i, status_message;
void *msg;
// Initialise the semaphore array
for (i = 0; i < NUM_CHOPSTICKS; i++) // Changed initialization loop
{
status_message = pthread_mutex_init(&chopstick[i], NULL);
// Check if the mutex is initialised successfully
if (status_message != 0) // Changed condition
{
printf("\n Mutex initialization failed");
exit(1);
}
}
// Run the philosopher Threads using *dine() function
for (i = 0; i < NUM_PHILOSOPHERS; i++) // Changed loop condition
{
status_message = pthread_create(&philosopher[i], NULL, (void *)dine, (void *)(intptr_t)i); // Cast i to void pointer
if (status_message != 0)
{
printf("\n Thread creation error \n");
exit(1);
}
}
// Wait for all philosophers threads to complete executing (finish dining) before closing the program
for (i = 0; i < NUM_PHILOSOPHERS; i++) // Changed loop condition
{
status_message = pthread_join(philosopher[i], &msg);
if (status_message != 0)
{
printf("\n Thread join failed \n");
exit(1);
}
}
// Destroy the chopstick Mutex array
for (i = 0; i < NUM_CHOPSTICKS; i++) // Changed loop condition
{
status_message = pthread_mutex_destroy(&chopstick[i]);
if (status_message != 0)
{
printf("\n Mutex Destroyed \n");
exit(1);
}
}
return 0;
}
void dine(void *ptr) // Changed function signature
{
int n = (intptr_t)ptr; // Cast back to int
printf("\nPhilosopher %d is thinking ", n);
// Philosopher picks up the left chopstick (wait)
pthread_mutex_lock(&chopstick[n]);
// Philosopher picks up the right chopstick (wait)
pthread_mutex_lock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);
// After picking up both the chopsticks, the philosopher starts eating
printf("\nPhilosopher %d is eating ", n);
sleep(3);
// Philosopher places down the left chopstick (signal)
pthread_mutex_unlock(&chopstick[n]);
// Philosopher places down the right chopstick (signal)
pthread_mutex_unlock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);
// Philosopher finishes eating
printf("\nPhilosopher %d Finished eating ", n);
}