-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
61 lines (55 loc) · 1.86 KB
/
main.cpp
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
#include "getblk.h"
getblk obj1;
//Newly created threads call this function for buffer allocation
void *processWantBuffers(void *threadarg)
{
bool getbuff;
struct thread_data *my_data;
my_data = (struct thread_data *) threadarg;
pthread_mutex_lock(&lock);
sleep(3);
cout << "Thread ID : " << my_data->thread_id ;
cout << " Block Number requested : " << my_data->blocknum << endl;
getbuff = obj1.getblock(my_data->blocknum,my_data->thread_id);
cout<<"\nTHREAD "<<my_data->thread_id<<" RELEASED BUFFER "<<my_data->blocknum<<"\n";
displayFL();
if(getbuff == true) //Check if there are any waiting processes in common waiting list or in the current buffer's waiting list
{
pthread_cond_broadcast(&cond); //Signal to wake up waiting processes
pthread_cond_broadcast(&cond1);
}
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
int main()
{
init(); //Initialising the Data Structures used
display(); //Displaying the initial state of Data Structures used
pthread_mutex_init(&lock, NULL);
pthread_t threads[8];
struct thread_data td[8];
srand(time(0));
for( int i = 1; i<= 8; i++ )
{
pthread_mutex_lock(&lock);
cout <<endl<< "THREAD "<< i <<" CREATED!! "<<endl;
sleep(1);
pthread_mutex_unlock(&lock);
td[i].thread_id = i;
td[i].blocknum = (rand() % 13)+1;
pthread_create(&threads[i], NULL, processWantBuffers, (void *)&td[i]);
}
//Broadcasting signals to the pending threads
int i= 1;
while(i<=8)
{
if(!pthread_join(threads[i],NULL))
{
pthread_cond_broadcast(&cond);
pthread_cond_broadcast(&cond1);
}
i++;
}
pthread_exit(NULL);
return 0;
}