-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprg7.c
150 lines (136 loc) · 2.71 KB
/
prg7.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <stdio.h>
#include<unistd.h>
#include <sched.h>
void main(int argc,char*argv[])
{
int pro,res;
printf("Enter number of processes & resources\n");
scanf("%d",&pro );
scanf("%d",&res );
int max[pro][res],alloc[pro][res],need[pro][res];
printf("Enter max matrix\n");
for(int i=0;i<pro;i++)
{
for(int j=0;j<res;j++)
{
scanf("%d",&max[i][j]);
}
}
printf("Enter alloc matrix\n");
for(int i=0;i<pro;i++)
{
for(int j=0;j<res;j++)
{
scanf("%d",&alloc[i][j]);
}
}
printf("Need matrix is\n" );
for(int i=0;i<pro;i++)
{
for(int j=0;j<res;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
printf("%d ",need[i][j] );
}printf("\n" );
}
printf("Enter the available resources\n" );
int avail[res];
for(int i=0;i<res;i++)
scanf("%d",&avail[i]);
//Request resource algo
int p;
printf("Enter process number which requests\n");
scanf("%d",&p );
printf("Enter request\n" );
int req[res];
for(int i=0;i<res;i++)
scanf("%d",&req[i]);
//if request <= need && request <= avail do the three
int flag=0;
printf("RESOURCE REQUEST\n" );
for(int i=0;i<res;i++)
{
if(req[i]<=avail[i]&&req[i]<=need[p][i])
flag=1;
else
{flag=0;break;}
}
if(flag==1)
printf("Request can be allocated\n" );
else
printf("Request cannot be allocated\n" );
for(int i=0;i<res;i++)
{
avail[i]-=req[i];
alloc[p][i]+=req[i];
need[p][i]-=req[i];
}
//safety algo
printf("New need matrix\n" );
for(int i=0;i<pro;i++)
{
for(int j=0;j<res;j++)
{
//need[i][j]=max[i][j]-alloc[i][j];
printf("%d ",need[i][j]);
}printf("\n");
}
int work[res];
printf("work mat: ");
for(int i=0;i<res;i++)
{
work[i]=avail[i];
printf("%d ",work[i]);
}//copied
printf("\n");
int count=0;
int finish[pro],k=0;
for(int i=0;i<pro;i++)
finish[i]=0;
int order[pro];
for(int i=0;i<pro;i=(i+1)%pro)
{
if(count>pro*pro)
break;
count++;
flag=0;
if(finish[i]==0)
{//unfinished
printf("Process %d\n",i );
for(int j=0;j<res;j++)
{
if(work[j]>=need[i][j])
flag=1;
else{
flag=0;
break;}
}
if(flag==1)//applicable for all resources
{
printf("applicable\n" );
for(int j=0;j<res;j++)
{
work[j]+=alloc[i][j];
}finish[i]=1;
order[k++]=i;
printf("available: " );
for(int x=0;x<res;x++)
printf("%d ",work[x] );
printf("\n" );
}
}
//check if all done
printf("k=%d\n",k );
if(k==pro)
{
printf("All processes accepted\n" );
//all done
break;
}
}
printf("The order is\n" );
for(int i=0;i<k;i++)
{
printf("%d\n",order[i] );
}
}