srtf最短剩余时间c++代码
时间: 2023-11-12 08:56:05 浏览: 226
下面是 SRTF (最短剩余时间优先) 调度算法的 C++ 代码示例:
```c++
#include <iostream>
#include <queue>
using namespace std;
struct Process {
int pid; // 进程 ID
int at; // 到达时间
int bt; // 运行时间
int rt; // 剩余运行时间
};
struct Compare {
bool operator()(const Process& a, const Process& b) {
return a.rt > b.rt; // 按照剩余时间从小到大排序
}
};
void srtf(Process processes[], int n) {
priority_queue<Process, vector<Process>, Compare> pq;
int current_time = 0;
int completed = 0;
int waiting_time = 0;
int turnaround_time = 0;
pq.push(processes[0]);
int i = 1;
while (completed < n) {
if (pq.empty()) {
pq.push(processes[i++]);
continue;
}
Process p = pq.top();
pq.pop();
if (p.rt == p.bt) { // 第一次被调度
waiting_time += current_time - p.at;
} else {
waiting_time += current_time - p.rt - p.at;
}
turnaround_time += current_time - p.at + p.bt - p.rt;
current_time += p.rt;
while (i < n && current_time >= processes[i].at) {
pq.push(processes[i++]);
}
completed++;
p.rt = 0;
pq.push(p);
}
cout << "Average waiting time = " << (float)waiting_time / n << endl;
cout << "Average turnaround time = " << (float)turnaround_time / n << endl;
}
int main() {
Process processes[] = {
{1, 0, 5, 5},
{2, 1, 3, 3},
{3, 2, 8, 8},
{4, 3, 6, 6},
{5, 4, 4, 4},
};
int n = sizeof(processes) / sizeof(Process);
srtf(processes, n);
return 0;
}
```
阅读全文