-
Notifications
You must be signed in to change notification settings - Fork 1
/
semaphores.c
61 lines (52 loc) · 1.96 KB
/
semaphores.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
// Adapted from: https://dextutor.com/process-synchronization-using-semaphores/
#include<pthread.h>
#include<stdio.h>
#include<semaphore.h>
#include<unistd.h>
void *fun1(); // inrement shared variable by 1
void *fun2(); // decrement shared variable by 1
int shared = 1; //shared variable
sem_t s; //semaphore variable
int main() {
/*
initialize semaphore variable
- 1st argument is address of variable,
- 2nd is number of processes sharing semaphore,
- 3rd argument is the initial value of semaphore variable
*/
sem_init(&s, 0, 1);
// create two threads
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
// wait for the threads to finish
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
// prints the last updated value of shared variable
printf("Final value of shared variable is %d\n",shared);
}
void *fun1() {
int x;
sem_wait(&s); //executes wait operation on s
x = shared; //thread1 reads value of shared variable
printf("Thread1 reads the value as %d\n",x);
x++; //thread1 increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread1 is preempted by thread 2
shared = x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
sleep(5);
sem_post(&s);
}
void *fun2() {
int y;
sem_wait(&s); //executes wait operation on s
y = shared; //thread2 reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread2 increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread2 is preempted by thread 1
shared = y; //thread2 updates the value of shared variable
printf("Value of shared variable updated by Thread2 is: %d\n",shared);
sem_post(&s);
}