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 */
17 #ifndef PTHREAD_ACCESSOR_H
18 #define PTHREAD_ACCESSOR_H
20 #include <pthread.h>
22 #include "private/bionic_macros.h"
23 #include "pthread_internal.h"
25 class pthread_accessor {
26 public:
27 explicit pthread_accessor(pthread_t desired_thread) {
28 Lock();
29 for (thread_ = g_thread_list; thread_ != NULL; thread_ = thread_->next) {
30 if (thread_ == reinterpret_cast<pthread_internal_t*>(desired_thread)) {
31 break;
32 }
33 }
34 }
36 ~pthread_accessor() {
37 Unlock();
38 }
40 void Unlock() {
41 if (is_locked_) {
42 is_locked_ = false;
43 thread_ = NULL;
44 pthread_mutex_unlock(&g_thread_list_lock);
45 }
46 }
48 pthread_internal_t& operator*() const { return *thread_; }
49 pthread_internal_t* operator->() const { return thread_; }
50 pthread_internal_t* get() const { return thread_; }
52 private:
53 pthread_internal_t* thread_;
54 bool is_locked_;
56 void Lock() {
57 pthread_mutex_lock(&g_thread_list_lock);
58 is_locked_ = true;
59 }
61 DISALLOW_COPY_AND_ASSIGN(pthread_accessor);
62 };
64 #endif // PTHREAD_ACCESSOR_H