Untitled

 avatar
unknown
plain_text
a year ago
2.0 kB
12
Indexable
#include <iostream>
#include <map>
#include <set>
#include <limits>

class GPUAllocator {
private:
    std::map<int, int> processToGPU; // Map process ID to GPU ID
    std::set<int> availableGPUs;     // Set of available GPU IDs

public:
    GPUAllocator() {
        // Initialize with a large number of GPUs for example purposes
        for (int i = 1; i <= std::numeric_limits<int>::max(); ++i) {
            availableGPUs.insert(i);
        }
    }

    void addProcess(int process_id) {
        if (availableGPUs.empty()) {
            std::cerr << "No available GPUs to allocate." << std::endl;
            return;
        }
        int gpu_id = *availableGPUs.begin(); // Get the smallest available GPU ID
        availableGPUs.erase(availableGPUs.begin()); // Remove it from available GPUs
        processToGPU[process_id] = gpu_id; // Assign it to the process
    }

    void removeProcess(int process_id) {
        auto it = processToGPU.find(process_id);
        if (it != processToGPU.end()) {
            int gpu_id = it->second;
            availableGPUs.insert(gpu_id); // Add the GPU back to available GPUs
            processToGPU.erase(it); // Remove the process from the map
        } else {
            std::cerr << "Process ID not found." << std::endl;
        }
    }

    int smallestUnoccupied() {
        if (availableGPUs.empty()) {
            std::cerr << "No unoccupied GPUs available." << std::endl;
            return -1; // Return an invalid ID to indicate no available GPUs
        }
        return *availableGPUs.begin(); // Return the smallest available GPU ID
    }
};

int main() {
    GPUAllocator allocator;
    allocator.addProcess(5);
    allocator.addProcess(2);
    std::cout << "Smallest unoccupied GPU: " << allocator.smallestUnoccupied() << std::endl;
    std::cout << "Smallest unoccupied GPU: " << allocator.smallestUnoccupied() << std::endl;
    allocator.removeProcess(5);
    std::cout << "Smallest unoccupied GPU: " << allocator.smallestUnoccupied() << std::endl;
    
    return 0;
}
Editor is loading...
Leave a Comment