blob: cbfd5a08aff8f5524cfe11cfa9432490a0d70842 [file] [log] [blame]
Elliott Hughes8daa0922011-09-11 13:46:25 -07001/*
2 * Copyright (C) 2011 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 ART_SRC_MUTEX_H_
18#define ART_SRC_MUTEX_H_
19
20#include <pthread.h>
21#include <string>
22
23#include "logging.h"
24#include "macros.h"
25
26namespace art {
27
28class Mutex {
29 public:
30 explicit Mutex(const char* name);
31 ~Mutex();
32
33 void Lock();
34
35 bool TryLock();
36
37 void Unlock();
38
39 const char* GetName() {
40 return name_.c_str();
41 }
42
43 pthread_mutex_t* GetImpl() {
44 return &mutex_;
45 }
46
47 void AssertHeld() {
48#ifdef __BIONIC__
49 DCHECK_EQ(GetOwner(), GetTid());
50#endif
51 }
52
53 void AssertNotHeld() {
54#ifdef __BIONIC__
55 DCHECK_NE(GetOwner(), GetTid());
56#endif
57 }
58
59 private:
60 pid_t GetOwner();
61 pid_t GetTid();
62
63 std::string name_;
64
65 pthread_mutex_t mutex_;
66
67 DISALLOW_COPY_AND_ASSIGN(Mutex);
68};
69
70class MutexLock {
71 public:
72 explicit MutexLock(Mutex& mu) : mu_(mu) {
73 mu_.Lock();
74 }
75
76 ~MutexLock() {
77 mu_.Unlock();
78 }
79
80 private:
81 Mutex& mu_;
82 DISALLOW_COPY_AND_ASSIGN(MutexLock);
83};
84
85} // namespace art
86
87#endif // ART_SRC_MUTEX_H_