blob: 4dba6b70daa2512b18289e7f0cd0e7a16430543f [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#include "mutex.h"
18
19#include <errno.h>
20
21#include "logging.h"
22#include "utils.h"
23
24namespace art {
25
26Mutex::Mutex(const char* name) : name_(name) {
27#ifndef NDEBUG
28 pthread_mutexattr_t debug_attributes;
29 errno = pthread_mutexattr_init(&debug_attributes);
30 if (errno != 0) {
31 PLOG(FATAL) << "pthread_mutexattr_init failed";
32 }
33#if VERIFY_OBJECT_ENABLED
34 errno = pthread_mutexattr_settype(&debug_attributes, PTHREAD_MUTEX_RECURSIVE);
35#else
36 errno = pthread_mutexattr_settype(&debug_attributes, PTHREAD_MUTEX_ERRORCHECK);
37#endif
38 if (errno != 0) {
39 PLOG(FATAL) << "pthread_mutexattr_settype failed";
40 }
41 errno = pthread_mutex_init(&mutex_, &debug_attributes);
42 if (errno != 0) {
43 PLOG(FATAL) << "pthread_mutex_init failed";
44 }
45 errno = pthread_mutexattr_destroy(&debug_attributes);
46 if (errno != 0) {
47 PLOG(FATAL) << "pthread_mutexattr_destroy failed";
48 }
49#else
50 errno = pthread_mutex_init(&mutex_, NULL);
51 if (errno != 0) {
52 PLOG(FATAL) << "pthread_mutex_init failed";
53 }
54#endif
55}
56
57Mutex::~Mutex() {
58 errno = pthread_mutex_destroy(&mutex_);
59 if (errno != 0) {
60 PLOG(FATAL) << "pthread_mutex_destroy failed";
61 }
62}
63
64void Mutex::Lock() {
65 int result = pthread_mutex_lock(&mutex_);
66 if (result != 0) {
67 errno = result;
68 PLOG(FATAL) << "pthread_mutex_lock failed";
69 }
70}
71
72bool Mutex::TryLock() {
73 int result = pthread_mutex_trylock(&mutex_);
74 if (result == EBUSY) {
75 return false;
76 }
77 if (result != 0) {
78 errno = result;
79 PLOG(FATAL) << "pthread_mutex_trylock failed";
80 }
81 return true;
82}
83
84void Mutex::Unlock() {
85 int result = pthread_mutex_unlock(&mutex_);
86 if (result != 0) {
87 errno = result;
88 PLOG(FATAL) << "pthread_mutex_unlock failed";
89 }
90}
91
92pid_t Mutex::GetOwner() {
93#ifdef __BIONIC__
94 return static_cast<pid_t>((mutex_.value >> 16) & 0xffff);
95#else
96 UNIMPLEMENTED(FATAL);
97 return 0;
98#endif
99}
100
101pid_t Mutex::GetTid() {
102 return art::GetTid();
103}
104
105} // namespace