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 |
#include <iostream> #include <queue> #include <vector> #include <cstdlib> #include <ctime> const int SERVER_CAPACITY = 5; // Number of tasks the server can handle at a time const int TASK_COUNT = 20; // Number of tasks to be simulated // Task class class Task { public: Task(int id) : id(id) {} int getId() const { return id; } private: int id; }; // CloudServer class class CloudServer { public: CloudServer(int capacity) : capacity(capacity), tasksProcessed(0) {} void addTask(const Task& task) { if (currentTasks.size() < capacity) { currentTasks.push(task); std::cout << "Added Task " << task.getId() << " to the server." << std::endl; } else { std::cout << "Server is at full capacity. Task " << task.getId() << " cannot be added." << std::endl; } } void processTasks() { while (!currentTasks.empty()) { Task task = currentTasks.front(); currentTasks.pop(); tasksProcessed++; std::cout << "Processed Task " << task.getId() << "." << std::endl; } } int getTasksProcessed() const { return tasksProcessed; } private: int capacity; int tasksProcessed; std::queue<Task> currentTasks; }; // Main function int main() { srand(static_cast<unsigned>(time(0))); CloudServer server(SERVER_CAPACITY); // Simulate adding tasks to the cloud server for (int i = 0; i < TASK_COUNT; ++i) { Task task(i + 1); server.addTask(task); } // Process all tasks in the server std::cout << "Processing tasks..." << std::endl; server.processTasks(); std::cout << "Total tasks processed: " << server.getTasksProcessed() << std::endl; return 0; } |
Explanation:
- Task Class:
- Represents a task with an
id
. Task(int id)
: Constructor to initialize the task with an ID.getId() const
: Returns the ID of the task.
Advertisement - Represents a task with an
- CloudServer Class:
capacity
: Maximum number of tasks the server can handle simultaneously.tasksProcessed
: Total number of tasks processed by the server.currentTasks
: A queue of tasks currently being handled by the server.addTask(const Task& task)
: Adds a task to the server if there is capacity. Otherwise, it prints a message indicating that the server is full.processTasks()
: Processes all tasks in the server queue. Each task is removed from the queue and processed.getTasksProcessed() const
: Returns the number of tasks that have been processed.
AdvertisementAdvertisement - Main Function:
- Initializes a
CloudServer
object with the specified capacity. - Adds a number of tasks to the server.
- Processes all tasks in the server.
- Prints the total number of tasks processed.
- Initializes a