-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdining_mutex.c
More file actions
96 lines (68 loc) · 1.56 KB
/
dining_mutex.c
File metadata and controls
96 lines (68 loc) · 1.56 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
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
91
92
93
94
//Program Implementing Dining Philosophers Problem Using Mutex and Threads
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
pthread_t philosopher[5];
pthread_mutex_t spoon[5];
void *dine(int n)
{ printf("\nPhilosopher %d is thinking ",n);
pthread_mutex_lock(&spoon[n]);
pthread_mutex_lock(&spoon[(n+1)%5]);
printf("\nPhilosopher %d is eating ",n);
sleep(1);
pthread_mutex_unlock(&spoon[n]);
pthread_mutex_unlock(&spoon[(n+1)%5]);
printf("\nPhilosopher %d Finished eating",n);
}
void main()
{ int i,err;
void *msg;
for(i=1;i<=5;i++)
{ err=pthread_mutex_init(&spoon[i],NULL);
if(err!=0)
{ printf("\n Mutex initialization for spoon failed");
exit(1);
}
}
for(i=1;i<=5;i++)
{ err=pthread_create(&philosopher[i],NULL,(void *)dine,(int *)i);
if(err!=0)
{ printf("\n Thread creation failed \n");
exit(1);
}
}
for(i=1;i<=5;i++)
{ err=pthread_join(philosopher[i],&msg);
if(err!=0)
{ printf("\n Thread join failed \n");
exit(1);
}
}
for(i=1;i<=5;i++)
{ err=pthread_mutex_destroy(&spoon[i]);
if(err!=0)
{ printf("\n Mutex spoon Destroyed \n");
exit(1);
}
}
}
/*
OUTPUT
===============
Philosopher 4 is thinking
Philosopher 4 is eating
Philosopher 1 is thinking
Philosopher 1 is eating
Philosopher 3 is thinking
Philosopher 2 is thinking
Philosopher 5 is thinking
Philosopher 4 Finished eating
Philosopher 3 is eating
Philosopher 1 Finished eating
Philosopher 5 is eating
Philosopher 3 Finished eating
Philosopher 2 is eating
Philosopher 5 Finished eating
Philosopher 2 Finished eating
*/