69 单例使用宏实现

本文详细介绍了如何使用宏判断Objective-C环境中的ARC(Automatic Reference Counting)或MRC(Manual Reference Counting),并提供了一种在两种环境中都能正确实现单例模式的方法。
1>判断是否是ARC环境:
可以用宏判断是否为ARC环境
#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif

2>定义宏的时候字符串连接:
// ## : 连接字符串和参数
#define singleton_h(name) + (instancetype)shared##name;
1>在ARC和MRC环境下单例的宏实现:
// ## : 连接字符串和参数
#define singleton_h(name) + (instancetype)shared##name;

#if __has_feature(objc_arc) // ARC

#define singleton_m(name) \
static id _instance; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [super allocWithZone:zone]; \
    }); \
    return _instance; \
} \
 \
+ (instancetype)shared##name \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [[self alloc] init]; \
    })
    return _instance; \
} \
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
    return _instance; \
}

#else // 非ARC

#define singleton_m(name) \
static id _instance; \
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
   static dispatch_once_t onceToken; \
   dispatch_once(&onceToken, ^{ \
    _instance = [super allocWithZone:zone]; \
}); \
    return _instance; \
} \
\
+ (instancetype)shared##name \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
    _instance = [[self alloc] init]; \
}); \
    return _instance; \
} \
\
- (oneway void)release \
{ \
\
} \
\
- (id)autorelease \
{ \
    return _instance; \
} \
\
- (id)retain \
{ \
    return _instance; \
} \
\
- (NSUInteger)retainCount \
{ \
    return 1; \
} \
\
+ (id)copyWithZone:(struct _NSZone *)zone \
{ \
    return _instance; \
}

#endif
内容概要:本文系统介绍了算术优化算法(AOA)的基本原理、核心思想及Python实现方法,并通过图像分割的实际案展示了其应用价值。AOA是一种基于种群的元启发式算法,其核心思想来源于四则运算,利用乘除运算进行全局勘探,加减运算进行局部开发,通过数学优化器加速函数(MOA)和数学优化概率(MOP)动态控制搜索过程,在全局探索与局部开发之间实现平衡。文章详细解析了算法的初始化、勘探与开发阶段的更新策略,并提供了完整的Python代码实现,结合Rastrigin函数进行测试验证。进一步地,以Flask框架搭建前后端分离系统,将AOA应用于图像分割任务,展示了其在实际工程中的可行性与高效性。最后,通过收敛速度、寻优精度等指标评估算法性能,并提出自适应参数调整、模型优化和并行计算等改进策略。; 适合人群:具备一定Python编程基础和优化算法基础知识的高校学生、科研人员及工程技术人员,尤其适合从事人工智能、图像处理、智能优化等领域的从业者;; 使用场景及目标:①理解元启发式算法的设计思想与实现机制;②掌握AOA在函数优化、图像分割等实际问题中的建模与求解方法;③学习如何将优化算法集成到Web系统中实现工程化应用;④为算法性能评估与改进提供实践参考; 阅读建议:建议读者结合代码逐行调试,深入理解算法流程中MOA与MOP的作用机制,尝试在不同测试函数上运行算法以观察性能差异,并可进一步扩展图像分割模块,引入更复杂的预处理或后处理技术以提升分割效果。
#undef TAG 2 #define TAG "GameThermalControl" 3 4 #include "GameThermalControl.h" 5 #include "FreqControl.h" 6 #include "FrameControl.h" 7 #include "GameInfoCenter.h" 8 #include "InfoReader.h" 9 #include "GameCallBackManager.h" 10 #include "ThreadPool.h" 11 12 ANDROID_SINGLETON_STATIC_INSTANCE(GameThermalControl); 13 14 GameThermalControl::GameThermalControl() : isInit(false), 15 lastLimit(ABSOLUTE_ZERO_TEN), 16 identifier("GameThermalControl") 17 { 18 mCpuStructure = InfoReader::getInstance().getCpuStructureMap(); 19 mGameListMonitor = std::make_shared<FileMonitor>(gameListPath); 20 mGameThermalMonitor = std::make_shared<FileMonitor>(gameThermalPath); 21 mHeavyGameRecorder = std::make_shared<GameListRecorder>(); 22 mThermalControlRecorder = std::make_shared<ThermalControlRecoder>(); 23 24 for (auto &[cluster, _] : mCpuStructure) { 25 int coreIndex = InfoReader::getInstance().getCoreIndex(cluster); 26 if (coreIndex >= 0) { 27 mClusterMap[coreIndex] = cluster; 28 } 29 } 30 mThermalControlRecorder->setClusterMap(mClusterMap); 31 FreqControl::getInstance().registerAuthority(identifier, PRIOLEVEL::PRIO_THERMAL, FREQCONTROLTYPE::RESTRICT); 32 } 33 34 GameThermalControl::~GameThermalControl() 35 { 36 } 37 38 void GameThermalControl::init(std::string &package, std::string &config) 39 { 40 std::scoped_lock lck(mActionMtx); 41 mGamePackage = package; 42 if (mGameListMonitor->isFileUpdated()) { 43 mHeavyGameRecorder->loadData(gameListPath); 44 } 45 if (mGameThermalMonitor->isFileUpdated()) { 46 mThermalControlRecorder->loadData(gameThermalPath); 47 } 48 parseConfig(config); 49 INFO("apply thermal control %s", mThermalControlRecorder->getModel(mHeavyGameRecorder->contains(mGamePackage)).c_str()); 50 GameCallBackManager::getInstance().onNotifyTemp("1"); 51 isInit = true; 52 runControlThread(); 53 } 54 55 void GameThermalControl::reset() 56 { 57 std::scoped_lock lck(mActionMtx); 58 releaseAllControl(); 59 GameCallBackManager::getInstance().onNotifyTemp("0"); 60 isInit = false; 61 mControlCv.notify_all(); 62 lastLimit = ABSOLUTE_ZERO_TEN; 63 } 64 65 void GameThermalControl::notifyTemp(float temp) 66 { 67 std::scoped_lock lck(mActionMtx); 68 if (!isInit) { 69 return; 70 } 71 INFO("max shell temp is %f", temp); 72 int calcTemp = temp * 10; 73 ThermalConfig limit; 74 int tempGear = mThermalControlRecorder->getLimit(limit, calcTemp, mHeavyGameRecorder->contains(mGamePackage)); 75 if (tempGear == lastLimit || (tempGear < lastLimit && calcTemp > lastLimit - THERMALTHRESHOLD)) { 76 return; 77 } 78 if (tempGear == ABSOLUTE_ZERO_TEN) { 79 releaseAllControl(); 80 } else { 81 INFO("do thermal control, temp is %f, temp gear %d", temp, tempGear); 82 doControl(limit, temp); 83 FreqControl::getInstance().formatFreqString(); 84 } 85 lastLimit = tempGear; 86 } 87 88 void GameThermalControl::redoAction() 89 { 90 std::scoped_lock lck(mActionMtx); 91 if (!isInit || lastLimit == ABSOLUTE_ZERO_TEN) { 92 return; 93 } 94 ThermalConfig limit; 95 int tempGear = mThermalControlRecorder->getLimit(limit, lastLimit, mHeavyGameRecorder->contains(mGamePackage)); 96 if (unlikely(lastLimit != tempGear)) { 97 WARNING("something wrong with temperature notification or recorder has been reset."); 98 return; 99 } 100 float temp = GPA::safetyDivide<float, float, float>(tempGear, 10.f); 101 doControl(limit, temp); 102 FreqControl::getInstance().reformatFreqString(); 103 } 104 105 void GameThermalControl::runControlThread() 106 { 107 auto task = [this] () { 108 std::mutex mtx; 109 std::unique_lock lck(mtx); 110 using namespace std::literals::chrono_literals; 111 while (isInit) { 112 if (mControlCv.wait_for(lck, 50s) == std::cv_status::timeout) { 113 VERBOSE("Thread time out"); 114 } 115 GameThermalControl::getInstance().redoAction(); 116 } 117 }; 118 mThreadPool->submitWorkWithID(task, THREADID::GAMETHERMALCTRL); 119 } 120 121 bool GameThermalControl::parseConfig(std::string &config) 122 { 123 std::map<std::string, std::string> configs; 124 GPA::parseFeature(config, configs); 125 if (configs.find(GAMETHERMALCONFIG) == configs.end() || configs[GAMETHERMALCONFIG].empty()) { 126 DEBUG("get cloud config failed"); 127 mThermalControlRecorder->clearCloudModel(); 128 return false; 129 } 130 Json::Value root; 131 if (!GPA::stringToJson(configs[GAMETHERMALCONFIG], root)) { 132 WARNING("parse config failed"); 133 mThermalControlRecorder->clearCloudModel(); 134 return false; 135 } 136 ThermalModel model; 137 Json::Value::Members tempPoints = root.getMemberNames(); 138 for (std::string &point : tempPoints) { 139 if (!GPA::isNumeric(point)) { 140 continue; 141 } 142 int temp = stoi(point); 143 ThermalConfig thermalConfig = {0, {}}; 144 if (parseThermalConfig(root[point], thermalConfig)) { 145 model.emplace(temp, std::move(thermalConfig)); 146 } 147 } 148 if (model.empty()) { 149 mThermalControlRecorder->clearCloudModel(); 150 return false; 151 } 152 mThermalControlRecorder->setCloudModel(model); 153 return true; 154 } 155 156 bool GameThermalControl::parseThermalConfig(Json::Value &root, ThermalConfig &config) 157 { 158 if (root == Json::nullValue || root.empty()) { 159 return false; 160 } 161 Json::Value::Members elements = root.getMemberNames(); 162 for (auto element : elements) { 163 if (element.size() < 2) { 164 continue; 165 } 166 switch (element[0]) { 167 case 'c': { 168 int idx = element[1] - '0'; 169 if (mClusterMap.find(idx) != mClusterMap.end()) { 170 config.cpuLevel[mClusterMap[idx]] = GPA::getJsonValue(root, element, -1); 171 } 172 break; 173 } 174 175 case 'f': 176 if (element == "fps") { 177 config.fps = GPA::getJsonValue(root, element, 0); 178 } 179 break; 180 181 default: 182 break; 183 } 184 } 185 return true; 186 } 187 188 void GameThermalControl::doControl(ThermalConfig &limit, float temp) 189 { 190 for (auto &[cluster, level] : limit.cpuLevel) { 191 if (!mCpuStructure.count(cluster)) { 192 continue; 193 } 194 if (level < 0) { 195 INFO("release freq control"); 196 FreqControl::getInstance().releaseCpuMaxControl(identifier, cluster); 197 } else { 198 INFO("do freq control %d:%d", mCpuStructure[cluster].cores.front(), level); 199 int realLevel = std::min(level, (int) (mCpuStructure[cluster].freqTable.size() - 1)); 200 u64 freq = mCpuStructure[cluster].freqTable[realLevel]; 201 FreqControl::getInstance().doCpuMaxControl(freq, identifier, cluster); 202 } 203 } 204 if (limit.fps <= 0) { 205 FrameControl::getInstance().releaseRequest(identifier, mGamePackage); 206 } else { 207 FrameControl::getInstance().makeControlRequest(identifier, mGamePackage, limit.fps, temp); 208 } 209 } 210 211 void GameThermalControl::releaseAllControl() 212 { 213 INFO("release all control"); 214 for (auto &[cluster, _] : mCpuStructure) { 215 FreqControl::getInstance().releaseCpuMaxControl(identifier, cluster); 216 } 217 FreqControl::getInstance().formatFreqString(); 218 FrameControl::getInstance().releaseRequest(identifier, mGamePackage); 219 }
07-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值