1 /* 2 * Copyright (c) 2021-2022 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 BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_THREAD_LOCAL_DATA_H 17 #define BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_THREAD_LOCAL_DATA_H 18 19 #include <mutex> 20 #include <thread> 21 #include <unordered_map> 22 23 #include "nocopyable.h" 24 25 namespace OHOS { 26 namespace AppExecFwk { 27 /* 28 * Tool class, used to save thread local data. 29 */ 30 template<typename T> 31 class ThreadLocalData { 32 public: 33 ThreadLocalData() = default; 34 ~ThreadLocalData() = default; 35 DISALLOW_COPY_AND_MOVE(ThreadLocalData); 36 37 /* 38 * Override type conversion method. 39 */ T()40 inline operator T() const 41 { 42 return Current(); 43 } 44 45 /* 46 * Override operator equal to save data. 47 */ 48 inline const ThreadLocalData<T> &operator=(const T &data) 49 { 50 Save(data); 51 return *this; 52 } 53 54 /* 55 * Override operator equal to nullptr, which can used to discard the saved data. 56 */ 57 inline const ThreadLocalData<T> &operator=(std::nullptr_t) 58 { 59 Discard(); 60 return *this; 61 } 62 63 private: Current()64 inline T Current() const 65 { 66 std::lock_guard<std::mutex> lock(mapLock_); 67 auto it = dataMap_.find(std::this_thread::get_id()); 68 if (it == dataMap_.end()) { 69 return T(); 70 } else { 71 return it->second; 72 } 73 } 74 Save(const T & data)75 inline void Save(const T &data) 76 { 77 std::lock_guard<std::mutex> lock(mapLock_); 78 dataMap_[std::this_thread::get_id()] = data; 79 } 80 Discard()81 inline void Discard() 82 { 83 std::lock_guard<std::mutex> lock(mapLock_); 84 (void)dataMap_.erase(std::this_thread::get_id()); 85 } 86 87 mutable std::mutex mapLock_; 88 std::unordered_map<std::thread::id, T> dataMap_; 89 }; 90 } // namespace AppExecFwk 91 } // namespace OHOS 92 93 #endif // #ifndef BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_THREAD_LOCAL_DATA_H 94