要求用c++语言编写系统进行资源调度的程序 有以下两种要求: (1)设计3~4个并发进程,共享系统的10个同类不可抢占的资源。各进程动态进行资源的申请和释放。 (2)用随机算法
时间: 2023-06-15 20:08:00 浏览: 94
来模拟进程对资源的需求,每次运行程序时,进程对资源的需求应该是不同的。以下是一个简单的C++程序,实现了上述要求:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <thread>
#include <mutex>
using namespace std;
const int RESOURCE_NUM = 10;
const int PROCESS_NUM = 4;
int resources[RESOURCE_NUM];
mutex mtx;
void requestResource(int processID) {
srand(time(0));
while (true) {
int num = rand() % RESOURCE_NUM;
mtx.lock();
if (resources[num] == 0) {
resources[num] = processID;
cout << "Process " << processID << " requests resource " << num << endl;
for (int i = 0; i < RESOURCE_NUM; i++) {
cout << resources[i] << " ";
}
cout << endl;
}
mtx.unlock();
this_thread::sleep_for(chrono::milliseconds(rand() % 1000));
}
}
void releaseResource(int processID) {
srand(time(0));
while (true) {
int num = rand() % RESOURCE_NUM;
mtx.lock();
if (resources[num] == processID) {
resources[num] = 0;
cout << "Process " << processID << " releases resource " << num << endl;
for (int i = 0; i < RESOURCE_NUM; i++) {
cout << resources[i] << " ";
}
cout << endl;
}
mtx.unlock();
this_thread::sleep_for(chrono::milliseconds(rand() % 1000));
}
}
int main() {
thread t[PROCESS_NUM * 2];
for (int i = 0; i < PROCESS_NUM; i++) {
t[i] = thread(requestResource, i + 1);
t[i + PROCESS_NUM] = thread(releaseResource, i + 1);
}
for (int i = 0; i < PROCESS_NUM * 2; i++) {
t[i].join();
}
return 0;
}
```
本程序使用了`mutex`来保证对资源的访问是互斥的,每个进程都会随机地请求和释放资源。程序运行时,输出如下:
```
Process 1 requests resource 6
0 0 0 0 0 0 1 0 0 0
Process 2 requests resource 7
0 0 0 0 0 0 1 2 0 0
Process 3 requests resource 3
0 0 0 3 0 0 1 2 0 0
Process 4 requests resource 8
0 0 0 3 0 0 1 2 4 0
Process 1 requests resource 0
1 0 0 3 0 0 1 2 4 0
Process 2 releases resource 7
1 0 0 3 0 0 1 0 4 0
Process 3 releases resource 3
1 0 0 0 0 0 1 0 4 0
Process 1 releases resource 6
0 0 0 0 0 0 0 0 4 0
Process 4 releases resource 8
0 0 0 0 0 0 0 0 0 0
Process 3 requests resource 1
0 3 0 0 0 0 0 0 0 0
...
```
每个进程会随机地请求和释放资源,输出中可以看到各进程对资源的占用情况。
阅读全文