-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync1.c
73 lines (54 loc) · 1.25 KB
/
sync1.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
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
sem_t s1, s2, mutex;
// Definition of functions
void buyPasta() {
// Implementation of the buyPasta function
}
void buyPesto() {
// Implementation of the buyPesto function
}
void eatDinner() {
// Implementation of the eatDinner function
}
void *A(void *arg) {
buyPasta();
printf("buy1 done\n");
sem_wait(&s1);
sem_wait(&mutex);
eatDinner();
printf("p1 entered shared resource\n");
sem_post(&mutex);
sem_post(&s2);
pthread_exit(NULL);
}
void *B(void *arg) {
buyPesto();
printf("buy2 done\n");
sem_wait(&s2);
sem_wait(&mutex);
eatDinner();
printf("p2 entered shared resource\n");
sem_post(&mutex);
sem_post(&s1);
pthread_exit(NULL);
}
int main() {
// Initialize semaphores
sem_init(&s1, 0, 1);
sem_init(&s2, 0, 1);
sem_init(&mutex, 0, 1);
// Create threads A and B
pthread_t threadA, threadB;
pthread_create(&threadA, NULL, A, NULL);
pthread_create(&threadB, NULL, B, NULL);
// Wait for threads to finish
pthread_join(threadA, NULL);
pthread_join(threadB, NULL);
// Destroy semaphores
sem_destroy(&s1);
sem_destroy(&s2);
sem_destroy(&mutex);
return 0;
}