1 /* 2 * Copyright (c) 2020-2021 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 GRAPHIC_LITE_GRAPHIC_MUTEX_H 17 #define GRAPHIC_LITE_GRAPHIC_MUTEX_H 18 #include "stdbool.h" 19 #include "stdint.h" 20 #ifdef _WIN32 21 #include <windows.h> 22 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__ 23 #include <pthread.h> 24 #else 25 #include "los_mux.h" 26 #endif // WIN32 27 #include "gfx_utils/heap_base.h" 28 29 namespace OHOS { 30 /** @brief graphic mutex adapter for different platform. */ 31 class GraphicMutex : public HeapBase { 32 public: 33 /** Default constructor */ GraphicMutex()34 GraphicMutex() 35 { 36 #ifdef _WIN32 37 mutex_ = CreateMutex(NULL, FALSE, NULL); 38 initFlag_ = (mutex_ != NULL); 39 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__ 40 initFlag_ = (pthread_mutex_init(&mutex_, NULL) == 0); 41 #else 42 initFlag_ = (LOS_MuxCreate(&mutex_) == LOS_OK); 43 #endif // WIN32 44 } 45 46 /** Default destructor */ ~GraphicMutex()47 ~GraphicMutex() 48 { 49 if (!initFlag_) { 50 return; 51 } 52 #ifdef _WIN32 53 CloseHandle(mutex_); 54 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__ 55 pthread_mutex_destroy(&mutex_); 56 #else 57 LOS_MuxDelete(mutex_); 58 #endif // WIN32 59 } 60 Lock()61 inline bool Lock() 62 { 63 if (!initFlag_) { 64 return false; 65 } 66 #ifdef _WIN32 67 return (WaitForSingleObject(mutex_, INFINITE) == WAIT_OBJECT_0); 68 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__ 69 return (pthread_mutex_lock(&mutex_) == 0); 70 #else 71 return (LOS_MuxPend(mutex_, LOS_WAIT_FOREVER) == LOS_OK); 72 #endif // WIN32 73 } 74 Unlock()75 inline bool Unlock() 76 { 77 if (!initFlag_) { 78 return false; 79 } 80 #ifdef _WIN32 81 return ReleaseMutex(mutex_); 82 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__ 83 return (pthread_mutex_unlock(&mutex_) == 0); 84 #else 85 return (LOS_MuxPost(mutex_) == LOS_OK); 86 #endif // WIN32 87 } 88 89 private: 90 bool initFlag_; 91 #ifdef _WIN32 92 HANDLE mutex_; 93 #elif defined __linux__ || defined __LITEOS__ || defined __APPLE__ 94 pthread_mutex_t mutex_; 95 #else 96 uint32_t mutex_; 97 #endif // WIN32 98 }; 99 } // namespace OHOS 100 #endif // GRAPHIC_LITE_GRAPHIC_MUTEX_H 101