-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathformH2O.c
83 lines (76 loc) · 1.97 KB
/
formH2O.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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
pthread_mutex_t criticalRegionMutex;
pthread_mutex_t threadMutex;
sem_t HSem;
sem_t OSem;
int HWaiting = 0;
int OWaiting = 0;
void* H(){
pthread_mutex_lock(&threadMutex);
pthread_mutex_lock(&criticalRegionMutex);
HWaiting++;
pthread_mutex_unlock(&criticalRegionMutex);
if(HWaiting>=2 && OWaiting >=1){
formH2O(1);
printf("H usado\n");
pthread_mutex_unlock(&threadMutex);
} else {
pthread_mutex_unlock(&threadMutex);
sem_wait(&HSem);
printf("H usado\n");
}
pthread_exit("");
}
void* O(){
pthread_mutex_lock(&threadMutex);
pthread_mutex_lock(&criticalRegionMutex);
OWaiting++;
pthread_mutex_unlock(&criticalRegionMutex);
if(HWaiting>=2 && OWaiting >=1){
formH2O(0);
printf("O usado\n");
pthread_mutex_unlock(&threadMutex);
} else {
pthread_mutex_unlock(&threadMutex);
sem_wait(&OSem);
printf("O usado\n");
}
pthread_exit("");
}
void formH2O(int isH){
pthread_mutex_lock(&criticalRegionMutex);
printf("Formando H2O...\n");
OWaiting-=1;
HWaiting-=2;
pthread_mutex_unlock(&criticalRegionMutex);
sem_post(&HSem);
if(isH>0){
sem_post(&OSem);
} else {
sem_post(&HSem);
}
}
int main(int argc, char **argv){
pthread_mutex_init(&criticalRegionMutex, NULL);
pthread_mutex_init(&threadMutex, NULL);
sem_init(&HSem, 0, 0);
sem_init(&OSem, 0, 0);
srand((unsigned)time(NULL));
int numberOfMolecules = 100;
pthread_t molecules[numberOfMolecules];
for(int i=0;i<numberOfMolecules; i++){
int isH = rand()%3;
if(isH>0){
pthread_create(&molecules[i], NULL, &H, (void *) i);
} else {
pthread_create(&molecules[i], NULL, &O, (void *) i);
}
}
for(int j=0; j<numberOfMolecules; j++){
pthread_join(molecules[j], NULL);
}
return 0;
}