1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef MUTEX_H_ 18 #define MUTEX_H_ 19 20 #include "pthread.h" 21 22 // Based on utils/threads.h, but tailored to build with the NDK and used unbundled. 23 // This is a simple wrapper over the pthread_mutex_t type. 24 class Mutex { 25 public: Mutex()26 Mutex() { 27 pthread_mutex_init(&mMutex, NULL); 28 } lock()29 int lock() { 30 return -pthread_mutex_lock(&mMutex); 31 } unlock()32 void unlock() { 33 pthread_mutex_unlock(&mMutex); 34 } ~Mutex()35 ~Mutex() { 36 pthread_mutex_destroy(&mMutex); 37 } 38 39 // A simple class that locks a given mutex on construction 40 // and unlocks it when it goes out of scope. 41 class Autolock { 42 public: Autolock(Mutex & mutex)43 Autolock(Mutex &mutex) : lock(&mutex) { 44 lock->lock(); 45 } ~Autolock()46 ~Autolock() { 47 lock->unlock(); 48 } 49 private: 50 Mutex *lock; 51 }; 52 53 private: 54 pthread_mutex_t mMutex; 55 56 // Disallow copy and assign. 57 Mutex(const Mutex&); 58 Mutex& operator=(const Mutex&); 59 }; 60 61 #endif // MUTEX_H_ 62