-
Notifications
You must be signed in to change notification settings - Fork 2
/
SJF.cpp
80 lines (78 loc) · 3.27 KB
/
SJF.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "scheduler.h"
void SJF(int size, process processes[])
{
sort(processes, processes + size, comparedByBurst);
int finished_processes = 0, processor[4], WillGoToTheQ[4], i = 0, pr;
memset(processor, -1, sizeof processor);
memset(WillGoToTheQ, -1, sizeof WillGoToTheQ);
CompareProcess cmp(processes);
priority_queue<int, vector<int>, CompareProcess> waiting(cmp); //O(logn)
for (int t = 0;; t++)
{
int idx_p = 0;
for (idx_p = 0; idx_p < 4 && i < size && processes[i].arrive_time <= t; ++idx_p) // if processor is idle and processes
{
if (processor[idx_p] == -1)
{
processor[idx_p] = i;
processes[i].current_brust_time = processes[i].phases[processes[i].phase_idx].first;
processes[i].state = processes[i].phases[processes[i].phase_idx].second;
processes[i].last_processor = idx_p;
i++;
}
}
while (i < size && processes[i].arrive_time <= t) // processes arrived but there is no place at cpu so it will go in waiting queue
{
processes[i].state = processes[i].phases[processes[i].phase_idx].second;
processes[i].current_brust_time = processes[i].phases[processes[i].phase_idx].first;
waiting.push(i);
i++;
}
for (idx_p = 0; idx_p < 4; idx_p++)
{
if (processor[idx_p] == -1) // means that , that processor is idle
{
output[t][idx_p] = "i";
if (!waiting.empty())
{
WillGoToTheQ[idx_p] = waiting.top();
waiting.pop();
}
continue;
}
pr = processor[idx_p]; // index of the process in the processor
output[t][idx_p] = processes[pr].process_name;
processes[pr].time_consumed++;
if (processes[pr].time_consumed == processes[pr].current_brust_time) // proceses finished exec
{
processes[pr].phase_idx++;
processes[pr].time_consumed = 0;
if (processes[pr].phase_idx < processes[pr].n_phases) // still want more ?
{
processes[pr].state = processes[pr].phases[processes[pr].phase_idx].second;
processes[pr].current_brust_time = processes[pr].phases[processes[pr].phase_idx].first;
}
else // process finished
{
finished_processes++;
processes[pr].state = 2;
processes[pr].complete_time = t;
processes[pr].turn_around_time = t - processes[pr].arrive_time;
}
if (!waiting.empty())
{
WillGoToTheQ[idx_p] = waiting.top();
waiting.pop();
}
processor[idx_p] = -1;
}
}
match_prefrences(processor, WillGoToTheQ, processes);
IO_handler_bypq(size, processes, waiting, finished_processes, t);
if (finished_processes == size)
{
print(t, processes, size);
return;
}
}
}