blob: df4a5a22bb7f90af6b611a73714954f14fc07f25 [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
Elliott Hughes8eac9af2014-05-09 19:12:08 -070022#include "private/bionic_macros.h"
Elliott Hughes9d23e042013-02-15 19:21:51 -080023#include "pthread_internal.h"
24
25class pthread_accessor {
26 public:
27 explicit pthread_accessor(pthread_t desired_thread) {
28 Lock();
Elliott Hughes1728b232014-05-14 10:02:03 -070029 for (thread_ = g_thread_list; thread_ != NULL; thread_ = thread_->next) {
Elliott Hughes9d23e042013-02-15 19:21:51 -080030 if (thread_ == reinterpret_cast<pthread_internal_t*>(desired_thread)) {
31 break;
32 }
33 }
34 }
35
36 ~pthread_accessor() {
37 Unlock();
38 }
39
Elliott Hughesfae89fc2013-02-21 11:22:23 -080040 void Unlock() {
41 if (is_locked_) {
42 is_locked_ = false;
43 thread_ = NULL;
Elliott Hughes1728b232014-05-14 10:02:03 -070044 pthread_mutex_unlock(&g_thread_list_lock);
Elliott Hughesfae89fc2013-02-21 11:22:23 -080045 }
46 }
47
Elliott Hughes9d23e042013-02-15 19:21:51 -080048 pthread_internal_t& operator*() const { return *thread_; }
49 pthread_internal_t* operator->() const { return thread_; }
50 pthread_internal_t* get() const { return thread_; }
51
52 private:
53 pthread_internal_t* thread_;
54 bool is_locked_;
55
56 void Lock() {
Elliott Hughes1728b232014-05-14 10:02:03 -070057 pthread_mutex_lock(&g_thread_list_lock);
Elliott Hughes9d23e042013-02-15 19:21:51 -080058 is_locked_ = true;
59 }
60
Elliott Hughes8eac9af2014-05-09 19:12:08 -070061 DISALLOW_COPY_AND_ASSIGN(pthread_accessor);
Elliott Hughes9d23e042013-02-15 19:21:51 -080062};
63
64#endif // PTHREAD_ACCESSOR_H