-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscheduler.cpp
More file actions
318 lines (278 loc) · 10.8 KB
/
scheduler.cpp
File metadata and controls
318 lines (278 loc) · 10.8 KB
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#include "scheduler.h"
#include <sstream>
#include <iomanip>
#include "config.h"
#include "VMstat.h"
Scheduler::Scheduler(int count, const std::string& schedulerType, int timeQuantum, int delayPerInstruction, IMemoryAllocator* allocator)
: coreCount(count),
schedulerType(schedulerType),
timeQuantum(timeQuantum),
delayPerInstruction(delayPerInstruction),
allocator(allocator),
cores(count, nullptr)
{}
//override scheduler constructor to handle case when no timeQuantum is given if type is fcfs
Scheduler::Scheduler(int count, const std::string& schedulerType, int delayPerInstruction, IMemoryAllocator* allocator)
: coreCount(count),
schedulerType(schedulerType),
delayPerInstruction(delayPerInstruction),
cores(count, nullptr),
allocator(allocator)
{}
void Scheduler::addProcess(Process* p)
{
std::unique_lock<std::mutex> lock(mtx);
processQueue.push(p);
cv.notify_all();
}
// Starts the scheduler by launching a thread for each CPU core.
void Scheduler::start()
{
for (int i = 0; i < coreCount; ++i)
{
coreThreads.emplace_back(&Scheduler::coreWorker, this, i);
}
}
// The main function executed by each CPU core thread.
// Implements the First-Come, First-Served (FCFS) scheduling logic.
void Scheduler::coreWorker(int coreId)
{
while (true)
{
Process* currentProcess = nullptr;
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] {
return !processQueue.empty() || shutdown;
});
if (shutdown && processQueue.empty()) {
if (cores[coreId] != nullptr) {
// If this core is still running a process, deallocate it
allocator->deallocate(cores[coreId]->getPID());
}
cores[coreId] = nullptr;
// check if ALL cores are now idle
if (getUsedCores() == 0) {
break; // safe to exit this core
} else {
// wait again for the last one to exit
std::this_thread::sleep_for(std::chrono::milliseconds(50));
continue;
}
}
// If queue is not empty, assign a process
if (!processQueue.empty()) {
currentProcess = processQueue.front();
processQueue.pop();
// Allocate memory if needed
//check if all pages are already there?
void* mem = nullptr;
if (currentProcess->getMemoryPtr() == nullptr && schedulerType == "fcfs") {
if (allocator->getFreeFrameList().size() == 0){
currentProcess->setMemoryPtr(nullptr);
processQueue.push(currentProcess);
{
//update vmstat
std::lock_guard<std::mutex> lock(vmstatMutex);
vmstats.idleCPUticks += 1; // Increment active CPU ticks
}
continue;
}
mem = allocator->allocate(currentProcess);
} else{
mem = allocator->allocate(currentProcess);
}
if (mem == nullptr) {
{
//update vmstat
std::lock_guard<std::mutex> lock(vmstatMutex);
vmstats.idleCPUticks += 1; // Increment active CPU ticks
}
processQueue.push(currentProcess);
cores[coreId] = nullptr;
continue;
}else {
//std::cout << "Core " << coreId << " running: " << currentProcess->getPID() << std::endl;
//when can it not run for rr?
//when the processes inside the cores take up all the frames
if (allocator->checkProcessFrames(currentProcess) == false){
processQueue.push(currentProcess);
cores[coreId] = nullptr;
{
//update vmstat
std::lock_guard<std::mutex> lock(vmstatMutex);
vmstats.idleCPUticks += 1; // Increment active CPU ticks
}
continue;
}else{
cores[coreId] = currentProcess;
currentProcess->setMemoryPtr(mem);
}
}
}
}
if (currentProcess->getMemoryPtr())
{
// Mark as running
currentProcess->setState(Process::RUNNING);
if (schedulerType == "fcfs")
{
while (!currentProcess->isFinished())
{
if (shutdown) break;
currentProcess->executeCurrentCommand(coreId);
currentProcess->moveToNextLine();
std::this_thread::sleep_for(std::chrono::milliseconds(delayPerInstruction));
{
//update vmstat
std::lock_guard<std::mutex> lock(vmstatMutex);
vmstats.activeCPUticks += 1; // Increment active CPU ticks
}
}
}
else if (schedulerType == "rr")
{
for (int i = 0; i < timeQuantum && !currentProcess->isFinished(); ++i)
{
if (shutdown) {
break;
}
//std::cout << "Core " << coreId << " executing process: " << currentProcess->getName() << std::endl;
if (allocator->checkProcessFrames(currentProcess) == false)
{
break; // skip execution if process is not in memory
}
currentProcess->executeCurrentCommand(coreId);
currentProcess->moveToNextLine();
std::this_thread::sleep_for(std::chrono::milliseconds(delayPerInstruction));
//std::cout << cores[coreId]->getPID() << " running on core " << coreId << std::endl;
//std::this_thread::sleep_for(std::chrono::milliseconds(3000)); // Simulate some delay for output clarity
}
{
std::unique_lock<std::mutex> lock(mtx);
quantumCounter++;
}
{
//update vmstat
std::lock_guard<std::mutex> lock(vmstatMutex);
vmstats.activeCPUticks += 1; // Increment active CPU ticks
}
}
std::unique_lock<std::mutex> lock(mtx);
if (currentProcess->isFinished())
{
currentProcess->setState(Process::FINISHED);
currentProcess->setFinishTime(currentTimestamp());
finishedProcesses.push_back(currentProcess);
allocator->deallocate(currentProcess->getPID());
}
else
{
currentProcess->setState(Process::READY);
processQueue.push(currentProcess); // RR puts it back if not finished
}
cores[coreId] = nullptr;
//update vmstat
}else{
std::lock_guard<std::mutex> lock(vmstatMutex);
vmstats.idleCPUticks+= 1; // Increment active CPU ticks
}
}
}
void Scheduler::stop()
{
{
std::unique_lock<std::mutex> lock(mtx); // Acquire lock
this->shutdown = true; // Set shutdown flag
} // Lock is released here
cv.notify_all(); // Notify all waiting core threads
}
// Waits for all core threads to finish their execution.
void Scheduler::wait()
{
for (auto& t : coreThreads)
{
if (t.joinable()) t.join(); // Join each thread
}
}
// Returns the current timestamp formatted as YYYY-MM-DD HH:MM:SS.
std::string Scheduler::currentTimestamp()
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
// Use std::put_time for formatting the time
ss << std::put_time(std::localtime(&in_time_t), "(%m/%d/%Y %H:%M:%S %p)");
return ss.str();
}
// Returns a vector of strings, each representing the status of a CPU core.
std::vector<std::string> Scheduler::getCoreStatus()
{
std::vector<std::string> status;
std::unique_lock<std::mutex> lock(mtx); // Acquire lock to access cores vector
for (int i = 0; i < coreCount; ++i)
{
if (cores[i] != nullptr)
{
status.push_back("Core " + std::to_string(i) + ": Running " + cores[i]->getName());
}
else
{
status.push_back("Core " + std::to_string(i) + ": Idle");
}
}
return status;
}
std::vector<std::string> Scheduler::getRunningProcesses()
{
std::vector<std::string> status;
std::unique_lock<std::mutex> lock(mtx); // Lock to safely access cores
for (int i = 0; i < cores.size(); ++i)
{
if (cores[i]) // if core is working on a process
{
Process* p = cores[i];
int done = p->getCommandCounter();
int total = p->getLinesOfCode();
std::string time_now = currentTimestamp();
status.push_back(p->getName() + " " + time_now + " Core: " + std::to_string(i) + " " +
std::to_string(done) + "/" + std::to_string(total));
}
}
return status;
}
std::unordered_map<int, std::string> Scheduler::getRunningProcessDetails()
{
std::unique_lock<std::mutex> lock(mtx); // Lock to safely access cores
std::unordered_map<int, std::string> runningDetails;
for (int i = 0; i < cores.size(); ++i)
{
if (cores[i]) // if core is working on a process
{
Process* p = cores[i];
runningDetails[p->getPID()] = p->getName();
}
}
return runningDetails;
}
// Returns a vector of strings, each representing a finished process.
std::vector<std::string> Scheduler::getFinishedProcesses()
{
std::vector<std::string> status;
std::unique_lock<std::mutex> lock(mtx); // Acquire lock
for (const auto& p : finishedProcesses)
{
int total = p->getLinesOfCode();
status.push_back(p->getName() + " " + p->getFinishTime() + " Finished " +
std::to_string(total) + "/" + std::to_string(total));
}
return status;
}
int Scheduler::getUsedCores() {
std::unique_lock<std::mutex> lock(mtx);
int used = 0;
for (const auto& p : cores) {
if (p != nullptr) used++;
}
return used;
}