1 /* 2 * Copyright (c) 2020 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 OHOS_MUTEX_LOCK_H 17 #define OHOS_MUTEX_LOCK_H 18 19 #include <pthread.h> 20 21 namespace OHOS { 22 template<typename T> 23 struct Lock { 24 public: LockLock25 explicit Lock(T &mutex) : mutex_(&mutex) 26 { 27 if (mutex_ != nullptr) { 28 mutex_->Lock(); 29 } 30 } 31 ~LockLock32 ~Lock() 33 { 34 if (mutex_ != nullptr) { 35 mutex_->UnLock(); 36 } 37 } 38 private: 39 T *mutex_; 40 }; 41 42 struct Mutex { 43 public: MutexMutex44 Mutex() 45 { 46 pthread_mutex_init(&mutex_, nullptr); 47 } 48 ~MutexMutex49 ~Mutex() 50 { 51 pthread_mutex_destroy(&mutex_); 52 } 53 LockMutex54 void Lock() 55 { 56 pthread_mutex_lock(&mutex_); 57 } 58 UnLockMutex59 void UnLock() 60 { 61 pthread_mutex_unlock(&mutex_); 62 } 63 private: 64 pthread_mutex_t mutex_; 65 }; 66 } // OHOS 67 #endif // OHOS_MUTEX_LOCK_H 68