-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhydrogen.c
96 lines (90 loc) · 2.77 KB
/
hydrogen.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
85
86
87
88
89
90
91
92
93
94
95
96
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<stdlib.h>
pthread_t thread_oxy; //Thread for oxygen
pthread_t thread_hydro; //Thread for oxygen
pthread_mutex_t lock; //Lock for oxy
pthread_mutex_t lock1;
pthread_cond_t oxy_cond;;
pthread_cond_t hydro_cond;;
void *status;
sem_t o; //Semaphore for oxy.
sem_t h; //Semaphore for oxy.
int oxy,hydro; //variables to get Count of oxygen and hydrogen from semaphore.
int count=0;
void *oxygen(void *); //Oxygen thread.
void *hydrogen(void *); //Hydrogen thread.
void bond()
{
printf("Bond is created%d\n",count);
count++; //To keep count of number of bond created.
}
int main()
{
sem_init(&o,0,0); //Initialize semaphore for oxygen.
sem_init(&h,0,0); //Initialize semaphore for hydrogen.
for(int k=0;k<10;k++) //Call Oxygen thread 10 times.
{
if(pthread_create(&thread_oxy, NULL, oxygen,NULL)) //Create Oxygen thread.
printf("Error while creating thread\n");
}
for(int k=0;k<20;k++) //Create Hydrogen 20 times.
{
if(pthread_create(&thread_hydro, NULL, hydrogen,NULL)) //Create Hydrogen thread.
printf("Error while creating thread");
}
pthread_join(thread_oxy,&status); //Join Oxygen thread.
pthread_join(thread_hydro,&status); //Join Hydrogen thread.
return 0;
}
void *oxygen(void *i)
{
pthread_mutex_lock(&lock); //Acquire Lock.
sem_post(&o);
if(sem_getvalue(&o, &oxy)) //Get value of oxygen semaphore.
printf("Error in getting value\n");
if(sem_getvalue(&h, &hydro)) //Get value of hydrogen semaphore.
printf("Error in getting value\n");
if(oxy>=1 && hydro>=2) //Check for bond condition.
{
bond();
sem_wait(&h); //Decrease Hydrogen count by 2.
sem_wait(&h);
sem_wait(&o); //Decrease Oxygen count by.
pthread_cond_signal(&oxy_cond); //Wake up one oxygen thread.
pthread_cond_signal(&hydro_cond); //Wake up two hydrogen thread.
pthread_cond_signal(&hydro_cond);
}
else
{
pthread_cond_wait(&oxy_cond,&lock); //Wait for bond to be formed.
}
pthread_mutex_unlock(&lock); //Unlock Mutex.
pthread_exit(0);
}
void *hydrogen(void *i)
{
pthread_mutex_lock(&lock);
sem_post(&h);
if(sem_getvalue(&o, &oxy))
printf("Error in getting value\n");
if(sem_getvalue(&h, &hydro))
printf("Error in getting value\n");
if(oxy>=1 && hydro>=2)
{
bond();
sem_wait(&h);
sem_wait(&h);
sem_wait(&o);
pthread_cond_signal(&oxy_cond);
pthread_cond_signal(&hydro_cond);
pthread_cond_signal(&hydro_cond);
}
else
{
pthread_cond_wait(&hydro_cond,&lock);
}
pthread_mutex_unlock(&lock);
pthread_exit(0);
}