blob: eb8c350905e6a090d7f5fd9e7286a8018e311314 [file] [log] [blame]
Elliott Hughes9d23e042013-02-15 19:21:51 -08001/*
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
24class 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 pthread_internal_t& operator*() const { return *thread_; }
40 pthread_internal_t* operator->() const { return thread_; }
41 pthread_internal_t* get() const { return thread_; }
42
43 private:
44 pthread_internal_t* thread_;
45 bool is_locked_;
46
47 void Lock() {
48 pthread_mutex_lock(&gThreadListLock);
49 is_locked_ = true;
50 }
51
52 void Unlock() {
53 if (is_locked_) {
54 is_locked_ = false;
55 thread_ = NULL;
56 pthread_mutex_unlock(&gThreadListLock);
57 }
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