Управление ресурсами однопроцессорных систем оперативной обработки. Реализуй код на С++
Смоделировать работу для простого случая (решение задачи без прерывания).
Смоделировать реализацию алгоритма SPT через алгоритм RR.
Построить характеристику I и II системы:
– среднее время пребывания короткой заявки в системе;
– степень загрузки процессора - вероятность занятого состояния.
Входными данными являются :
– вероятность прихода сложной заявки (R)(в процентах);
– максимальная длительность решения сложной задачи (L);
– длительность кванта времени, уделяемого одной задаче (LK).
R=40
L = 7
LK < 4
Assistant
Here is the C++ code that simulates the management of resources in single-processor real-time processing systems as per your requirements:
cpp
#include <iostream>
#include <queue>
#include <vector>
#include <random>
#include <algorithm>
struct Task {
int id;
double arrival_time;
double processing_time;
double remaining_time;
bool is_complex;
double start_time;
double finish_time;
};
double getRandomProbability(std::mt19937 &gen) {
std::uniform_real_distribution<> dis(0.0, 1.0);
return dis(gen);
}
double getProcessingTime(bool is_complex, std::mt19937 &gen) {
if (is_complex) {
// Complex tasks have processing time between 4 and 7
std::uniform_real_distribution<> dis(4.0, 7.0);
return dis(gen);
} else {
// Short tasks have processing time between 1 and 3
std::uniform_real_distribution<> dis(1.0, 3.0);
return dis(gen);
}
}
void simulate_non_preemptive(int total_time, double arrival_rate, double R, int &total_short_tasks, double &sum_short_times, double &processor_busy_time) {
std::mt19937 gen(42); // Random number generator with a fixed seed
std::queue<Task> task_queue;
std::vector<Task> completed_tasks;
double current_time = 0.0;
bool processor_busy = false;
Task current_task;
int task_id_counter = 0;
while (current_time < total_time) {
// Check for task arrival
if (getRandomProbability(gen) < arrival_rate) {
bool is_complex = getRandomProbability(gen) < R;
double processing_time = getProcessingTime(is_complex, gen);
Task new_task = {task_id_counter++, current_time, processing_time, processing_time, is_complex, -1.0, -1.0};
task_queue.push(new_task);
}
if (!processor_busy && !task_queue.empty()) {
// Fetch next task
current_task = task_queue.front();
task_queue.pop();
current_task.start_time = current_time;
processor_busy = true;
}
if (processor_busy) {
// Process current task to completion
current_time += current_task.remaining_time;
processor_busy_time += current_task.remaining_time;
current_task.finish_time = current_time;
completed_tasks.push_back(current_task);
processor_busy = false;
} else {
// Idle time
current_time += 0.1; // Increment time by a small amount if processor is idle
}
}
// Calculate statistics
for (const auto &task : completed_tasks) {
if (!task.is_complex) {
total_short_tasks++;
sum_short_times += (task.finish_time - task.arrival_time);
}
}
}
void simulate_round_robin(int total_time, double arrival_rate, double R, double LK, int &total_short_tasks, double &sum_short_times, double &processor_busy_time) {
std::mt19937 gen(42); // Random number generator with a fixed seed
std::deque<Task> task_queue;
std::vector<Task> completed_tasks;
double current_time = 0.0;
int task_id_counter = 0;
while (current_time < total_time) {
// Check for task arrival
if (getRandomProbability(gen) < arrival_rate) {
bool is_complex = getRandomProbability(gen) < R;
double processing_time = getProcessingTime(is_complex, gen);
Task new_task = {task_id_counter++, current_time, processing_time, processing_time, is_complex, -1.0, -1.0};
task_queue.push_back(new_task);
}
if (!task_queue.empty()) {
// Get the next task in the queue
Task ¤t_task = task_queue.front();
if (current_task.start_time < 0.0) {
current_task.start_time = current_time;
}
// Process for LK units or until completion
double time_slice = std::min(LK, current_task.remaining_time);
current_task.remaining_time -= time_slice;
current_time += time_slice;
processor_busy_time += time_slice;
if (current_task.remaining_time <= 0.0) {
// Task is completed
current_task.finish_time = current_time;
completed_tasks.push_back(current_task);
task_queue.pop_front();
} else {
// Move task to end of queue
task_queue.pop_front();
task_queue.push_back(current_task);
}
} else {
// No tasks to process
current_time += 0.1; // Increment time by a small amount if processor is idle
}
}
// Calculate statistics
for (const auto &task : completed_tasks) {
if (!task.is_complex) {
total_short_tasks++;
sum_short_times += (task.finish_time - task.arrival_time);
}
}
}
int main() {
int total_time = 1000;
double arrival_rate = 0.5; // Average rate of task arrivals per time unit
double R = 0.4; // Probability of complex task
double LK = 2.0; // Time quantum for RR (LK < 4)
// Simulation 1: Non-preemptive (simple case)
int total_short_tasks_np = 0;
double sum_short_times_np = 0.0;
double processor_busy_time_np = 0.0;
simulate_non_preemptive(total_time, arrival_rate, R, total_short_tasks_np, sum_short_times_np, processor_busy_time_np);
std::cout << "Simulation 1: Non-preemptive scheduling" << std::endl;
if (total_short_tasks_np > 0) {
std::cout << "Average time short tasks spend in system: " << (sum_short_times_np / total_short_tasks_np) << std::endl;
} else {
std::cout << "No short tasks were processed." << std::endl;
}
std::cout << "Processor utilization: " << (processor_busy_time_np / total_time) * 100 << "%" << std::endl;
// Simulation 2: Round Robin scheduling
int total_short_tasks_rr = 0;
double sum_short_times_rr = 0.0;
double processor_busy_time_rr = 0.0;
simulate_round_robin(total_time, arrival_rate, R, LK, total_short_tasks_rr, sum_short_times_rr, processor_busy_time_rr);
std::cout << "\nSimulation 2: Round Robin scheduling" << std::endl;
if (total_short_tasks_rr > 0) {
std::cout << "Average time short tasks spend in system: " << (sum_short_times_rr / total_short_tasks_rr) << std::endl;
} else {
std::cout << "No short tasks were processed." << std::endl;
}
std::cout << "Processor utilization: " << (processor_busy_time_rr / total_time) * 100 << "%" << std::endl;
return 0;
}
Explanation:
This code performs the following:
Simulation of the Simple Case (Non-preemptive Scheduling):
Tasks are generated with a certain arrival rate.
Each task is either complex or short based on the given probability R.
Processing times for complex and short tasks are randomly generated within specified ranges.
Tasks are processed in a first-come, first-served manner without interruption.
Statistics are collected for the average time short tasks spend in the system and the processor utilization.
Simulation of the SPT Algorithm via the RR Algorithm:
A Round Robin scheduler is implemented with the time quantum LK.
Tasks are processed for a maximum of LK time units before being preempted and placed back in the queue if not completed.
The same task generation logic as the non-preemptive simulation is used.
Statistics are again collected for comparison.
Output of the Simulation Results:
For each simulation, the average time short tasks spend in the system and the processor utilization are printed.
Notes:
The random number generator is seeded with a fixed value to ensure reproducibility.
The getProcessingTime function generates processing times within specified ranges for complex and short tasks.
The simulations run for a total simulated time of 1000 units.
Processor utilization is calculated as the ratio of processor busy time to total simulation time.
Assumptions Made:
Arrival of tasks follows a probability based on the arrival rate.
Processing times for tasks are uniformly distributed within their respective ranges.
Time advances in small increments when the processor is idle to simulate time passing.
Feel free to adjust the parameters like total_time, arrival_rate, R, and LK as per your specific requirements.