-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemaphore.c
45 lines (36 loc) · 853 Bytes
/
Semaphore.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
/*Write a program that demonstrates how two processes can share a variable using semaphore */
#include <stdio.h>
int count = 5;
void wait(int *S); // Declaring functions
void signal(int *S);
int p2(int *S);
void wait(int *S){
while(*S<=0);
(*S)--;
}
void signal(int *S)
{
(*S)++;
}
void p1(int *S){
wait(S);
count++; //critical section
printf("Count changed by p1 is %d \n ",count);
signal(S);
wait(S);
int p= p2(&S);
printf("Count changed by p is %d \n",p);
signal(S);
}
int p2(int *S){
wait(S);
count--; //critical section
printf("Count changed by p2 is %d \n",count);
signal(S);
return count;
}
int main(){
int S=1; //semaphore variable
p1(&S);
p2(&S);
}