-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPetersons_mutex.c
84 lines (66 loc) · 1.61 KB
/
Petersons_mutex.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
// Use below command to compile:
// gcc -pthread peterson's_mutex.c -o peterson_mutex
#include <stdio.h>
#include <pthread.h>
int flag[2];
int turn;
const int MAX = 1e9;
int ans = 0;
void lock_init()
{
// Initialize lock by resetting the desire of
// both the threads to acquire the locks.
// And, giving turn to one of them.
flag[0] = flag[1] = 0;
turn = 0;
}
// Executed before entering critical section
void lock(int self)
{
// Set flag[self] = 1 saying you want to acquire lock
flag[self] = 1;
// But, first give the other thread the chance to
// acquire lock
turn = 1-self;
// Wait until the other thread looses the desire
// to acquire lock or it is your turn to get the lock.
while (flag[1-self]==1 && turn==1-self) ;
}
// Executed after leaving critical section
void unlock(int self)
{
// You do not desire to acquire lock in future.
// This will allow the other thread to acquire
// the lock.
flag[self] = 0;
}
// A Sample function run by two threads created
// in main()
void* func(void *s)
{
int i = 0;
int self = (int *)s;
printf("Thread Entered: %d\n", self);
lock(self);
// Critical section (Only one thread
// can enter here at a time)
for (i=0; i<MAX; i++)
ans++;
unlock(self);
}
// Driver code
int main()
{
// Initialized the lock then fork 2 threads
pthread_t p1, p2;
lock_init();
// Create two threads (both run func)
pthread_create(&p1, NULL, func, (void*)0);
pthread_create(&p2, NULL, func, (void*)1);
// Wait for the threads to end.
pthread_join(p1, NULL);
pthread_join(p2, NULL);
printf("Actual Count: %d | Expected Count: %d\n",
ans, MAX*2);
return 0;
}