1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef MAPLE_UTIL_INCLUDE_THREAD_STATUS_H 17 #define MAPLE_UTIL_INCLUDE_THREAD_STATUS_H 18 #include <thread> 19 #include <mutex> 20 #include <unordered_map> 21 22 namespace maple { 23 class ThreadEnv { 24 public: IsMeParallel()25 static bool IsMeParallel() 26 { 27 return threadEnv.isMeParallel; 28 } 29 SetMeParallel(bool status)30 static void SetMeParallel(bool status) 31 { 32 threadEnv.isMeParallel = status; 33 } 34 GetThreadIndex(const std::thread::id & tid)35 static size_t GetThreadIndex(const std::thread::id &tid) 36 { 37 static std::mutex mtx; 38 std::lock_guard<std::mutex> guard(mtx); 39 auto it = threadEnv.threadIndexMap.find(tid); 40 if (it != threadEnv.threadIndexMap.end()) { 41 return it->second; 42 } 43 return 0; // the index of main thread is 0 44 } 45 InitThreadIndex(const std::thread::id & tid)46 static void InitThreadIndex(const std::thread::id &tid) 47 { 48 static std::mutex mtx; 49 std::lock_guard<std::mutex> guard(mtx); 50 size_t currThreadCnt = threadEnv.threadIndexMap.size(); 51 threadEnv.threadIndexMap[tid] = (currThreadCnt + 1); 52 } 53 54 private: 55 static ThreadEnv threadEnv; 56 bool isMeParallel = false; // whether me is under multithreading (optimize separate functions in parallel) 57 // thread index begins from 1. 0 is reserved for main thread, which is not in the map 58 std::unordered_map<std::thread::id, size_t> threadIndexMap; 59 }; 60 61 class ParallelGuard { 62 public: mtx(mtxInput)63 explicit ParallelGuard(std::mutex &mtxInput, bool cond = true) : mtx(mtxInput), condition(cond) 64 { 65 if (condition) { 66 mtx.lock(); 67 } 68 } 69 70 ParallelGuard(const ParallelGuard &) = delete; 71 ParallelGuard &operator=(const ParallelGuard &) = delete; 72 ~ParallelGuard()73 ~ParallelGuard() 74 { 75 if (condition) { 76 mtx.unlock(); 77 } 78 } 79 80 private: 81 std::mutex &mtx; 82 const bool condition; 83 }; 84 } // namespace maple 85 #endif // MAPLE_UTIL_INCLUDE_THREAD_STATUS_H 86