1 /* 2 * Copyright (C) 2013 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 PTHREAD_ACCESSOR_H 18 #define PTHREAD_ACCESSOR_H 19 20 #include <pthread.h> 21 22 #include "pthread_internal.h" 23 24 class pthread_accessor { 25 public: 26 explicit pthread_accessor(pthread_t desired_thread) { 27 Lock(); 28 for (thread_ = gThreadList; thread_ != NULL; thread_ = thread_->next) { 29 if (thread_ == reinterpret_cast<pthread_internal_t*>(desired_thread)) { 30 break; 31 } 32 } 33 } 34 35 ~pthread_accessor() { 36 Unlock(); 37 } 38 39 void Unlock() { 40 if (is_locked_) { 41 is_locked_ = false; 42 thread_ = NULL; 43 pthread_mutex_unlock(&gThreadListLock); 44 } 45 } 46 47 pthread_internal_t& operator*() const { return *thread_; } 48 pthread_internal_t* operator->() const { return thread_; } 49 pthread_internal_t* get() const { return thread_; } 50 51 private: 52 pthread_internal_t* thread_; 53 bool is_locked_; 54 55 void Lock() { 56 pthread_mutex_lock(&gThreadListLock); 57 is_locked_ = true; 58 } 59 60 // Disallow copy and assignment. 61 pthread_accessor(const pthread_accessor&); 62 void operator=(const pthread_accessor&); 63 }; 64 65 #endif // PTHREAD_ACCESSOR_H 66