磁盘调度算法c++
时间: 2023-08-03 20:18:46 浏览: 121
磁盘调度算法是操作系统中的一种重要算法,用于调度硬盘上的读写请求。常见的磁盘调度算法有FCFS、SSTF、SCAN、C-SCAN等。以下是一个简单的磁盘调度算法的C++代码示例,仅供参考:
```c++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// 定义存储磁盘请求的结构体
struct Request {
int track; // 磁道号
int time; // 到达时间
};
// FCFS磁盘调度算法
void FCFS(vector<Request>& req, int start) {
int curr = start; // 当前磁道号
int total = 0; // 总移动距离
for (int i = 0; i < req.size(); i++) {
total += abs(curr - req[i].track);
curr = req[i].track;
}
cout << "FCFS: " << total << endl;
}
// SSTF磁盘调度算法
void SSTF(vector<Request>& req, int start) {
int curr = start;
int total = 0;
while (!req.empty()) {
int idx = 0, min_dist = INT_MAX;
for (int i = 0; i < req.size(); i++) {
int dist = abs(curr - req[i].track);
if (dist < min_dist) {
idx = i;
min_dist = dist;
}
}
total += min_dist;
curr = req[idx].track;
req.erase(req.begin() + idx);
}
cout << "SSTF: " << total << endl;
}
// SCAN磁盘调度算法
void SCAN(vector<Request>& req, int start, int end) {
int curr = start;
int total = 0;
vector<Request> left, right;
for (int i = 0; i < req.size(); i++) {
if (req[i].track < start) left.push_back(req[i]);
else if (req[i].track > end) right.push_back(req[i]);
else continue;
}
sort(left.begin(), left.end(), [](Request& a, Request& b) { return a.track > b.track; });
sort(right.begin(), right.end(), [](Request& a, Request& b) { return a.track < b.track; });
for (int i = 0; i < left.size(); i++) {
total += abs(curr - left[i].track);
curr = left[i].track;
}
total += end - start;
curr = end;
for (int i = 0; i < right.size(); i++) {
total += abs(curr - right[i].track);
curr = right[i].track;
}
cout << "SCAN: " << total << endl;
}
// C-SCAN磁盘调度算法
void CSCAN(vector<Request>& req, int start, int end) {
int curr = start;
int total = 0;
vector<Request> left, right;
for (int i = 0; i < req.size(); i++) {
if (req[i].track < start) left.push_back(req[i]);
else if (req[i].track > end) right.push_back(req[i]);
else continue;
}
sort(left.begin(), left.end(), [](Request& a, Request& b) { return a.track > b.track; });
sort(right.begin(), right.end(), [](Request& a, Request& b) { return a.track < b.track; });
for (int i = 0; i < left.size(); i++) {
total += abs(curr - left[i].track);
curr = left[i].track;
}
total += end - start;
curr = end;
for (int i = 0; i < right.size(); i++) {
total += abs(curr - right[i].track);
curr = right[i].track;
}
curr = start;
for (int i = 0; i < left.size(); i++) {
total += abs(curr - left[i].track);
curr = left[i].track;
}
cout << "C-SCAN: " << total << endl;
}
int main() {
vector<Request> req { {55, 0}, {58, 3}, {39, 8}, {18, 13}, {90, 17}, {160, 22}, {150, 28}, {38, 39} };
FCFS(req, 50);
SSTF(req, 50);
SCAN(req, 50, 200);
CSCAN(req, 50, 200);
return 0;
}
```
以上代码实现了四种磁盘调度算法:FCFS、SSTF、SCAN、C-SCAN。其中,FCFS算法按照请求的先后顺序依次处理,SSTF算法每次选择离当前磁道号最近的请求,SCAN算法按照磁道号方向依次处理,C-SCAN算法则是在SCAN算法的基础上,将磁道号从尾部到头部再处理一遍。
阅读全文