#include "GpuRgbMemoryFactory.h" GpuRgbMemoryFactory::GpuRgbMemoryFactory(){ // TODO 这里起一个定时器线程,清理超过一定时间如30s没有使用过的mem,避免出现可能的高显存占用情形 // 清理的时候注意线程安全性 } GpuRgbMemory* GpuRgbMemoryFactory::getMemory(int size, string id, string gpuid){ std::lock_guard lck (mtx); // 需要加锁 auto it = memoryMap.find(id); if (it != memoryMap.end()){ GpuRgbMemory* mem = it->second; if (mem){ if(mem->getId() == id && mem->getSize() == size && mem->getGpuId() == gpuid){ if (mem->isIsused() == false){ // 找到了,且未使用 mem->setIsused(true); return mem; }else{ // 找到了,但是在使用中 return nullptr; } }else{ // 找到了,但是不符合现在的需求,删除原有的,重新分配 delete mem; mem = nullptr; memoryMap.erase(it); } } } // 没有找到,或者找到了但是不符合需求重新分配 GpuRgbMemory* mem = nullptr; //new GpuRgbMemory(size, true, id, gpuid); memoryMap[id] = mem; return mem; } // 显存置为未使用状态 void GpuRgbMemoryFactory::releaseMemory(string id){ std::lock_guard lck (mtx); auto it = memoryMap.find(id); if (it != memoryMap.end()){ GpuRgbMemory* mem = it->second; if (mem){ mem->setIsused(false); } } }