-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem-12
More file actions
62 lines (48 loc) · 1.76 KB
/
problem-12
File metadata and controls
62 lines (48 loc) · 1.76 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_PHILOSOPHERS 5
pthread_mutex_t chopsticks[NUM_PHILOSOPHERS];
// Function to simulate philosopher's lifecycle
void* philosopherLifeCycle(void* arg) {
int id = *((int*)arg); // Get philosopher ID
int left_chopstick = id; // Left chopstick is same as philosopher's ID
int right_chopstick = (id + 1) % NUM_PHILOSOPHERS; // Right chopstick is the next one in the array
while (1) {
// Think
printf("Philosopher %d is thinking...\n", id);
// Pick up chopsticks
pthread_mutex_lock(&chopsticks[left_chopstick]);
pthread_mutex_lock(&chopsticks[right_chopstick]);
// Eat
printf("Philosopher %d is eating...\n", id);
sleep(rand() % 3 + 1); // Simulate eating time
// Put down chopsticks
pthread_mutex_unlock(&chopsticks[left_chopstick]);
pthread_mutex_unlock(&chopsticks[right_chopstick]);
// Repeat the cycle
}
}
int main() {
pthread_t philosophers[NUM_PHILOSOPHERS];
int philosopher_ids[NUM_PHILOSOPHERS];
// Initialize mutex locks for chopsticks
for (int i = 0; i < NUM_PHILOSOPHERS; ++i) {
pthread_mutex_init(&chopsticks[i], NULL);
}
// Create philosopher threads
for (int i = 0; i < NUM_PHILOSOPHERS; ++i) {
philosopher_ids[i] = i;
pthread_create(&philosophers[i], NULL, philosopherLifeCycle, (void*)&philosopher_ids[i]);
}
// Wait for threads to finish (although they run indefinitely)
for (int i = 0; i < NUM_PHILOSOPHERS; ++i) {
pthread_join(philosophers[i], NULL);
}
// Destroy mutex locks
for (int i = 0; i < NUM_PHILOSOPHERS; ++i) {
pthread_mutex_destroy(&chopsticks[i]);
}
return 0;
}