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