1 /*
2 * Copyright (C) 2009 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 "rsSignal.h"
18 #include <errno.h>
19
20 using namespace android;
21 using namespace android::renderscript;
22
23
Signal()24 Signal::Signal() {
25 mSet = true;
26 }
27
~Signal()28 Signal::~Signal() {
29 pthread_mutex_destroy(&mMutex);
30 pthread_cond_destroy(&mCondition);
31 }
32
init()33 bool Signal::init() {
34 int status = pthread_mutex_init(&mMutex, nullptr);
35 if (status) {
36 ALOGE("LocklessFifo mutex init failure");
37 return false;
38 }
39
40 status = pthread_cond_init(&mCondition, nullptr);
41 if (status) {
42 ALOGE("LocklessFifo condition init failure");
43 pthread_mutex_destroy(&mMutex);
44 return false;
45 }
46
47 return true;
48 }
49
set()50 void Signal::set() {
51 int status;
52
53 status = pthread_mutex_lock(&mMutex);
54 if (status) {
55 ALOGE("LocklessCommandFifo: error %i locking for set condition.", status);
56 return;
57 }
58
59 mSet = true;
60
61 status = pthread_cond_signal(&mCondition);
62 if (status) {
63 ALOGE("LocklessCommandFifo: error %i on set condition.", status);
64 }
65
66 status = pthread_mutex_unlock(&mMutex);
67 if (status) {
68 ALOGE("LocklessCommandFifo: error %i unlocking for set condition.", status);
69 }
70 }
71
wait(uint64_t timeout)72 bool Signal::wait(uint64_t timeout) {
73 int status;
74 bool ret = false;
75
76 status = pthread_mutex_lock(&mMutex);
77 if (status) {
78 ALOGE("LocklessCommandFifo: error %i locking for condition.", status);
79 return false;
80 }
81
82 if (!mSet) {
83 if (!timeout) {
84 status = pthread_cond_wait(&mCondition, &mMutex);
85 } else {
86 #if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
87 status = pthread_cond_timeout_np(&mCondition, &mMutex, timeout / 1000000);
88 #else
89 // This is safe it will just make things less reponsive
90 status = pthread_cond_wait(&mCondition, &mMutex);
91 #endif
92 }
93 }
94
95 if (!status) {
96 mSet = false;
97 ret = true;
98 } else {
99 #ifndef RS_SERVER
100 if (status != ETIMEDOUT) {
101 ALOGE("LocklessCommandFifo: error %i waiting for condition.", status);
102 }
103 #endif
104 }
105
106 status = pthread_mutex_unlock(&mMutex);
107 if (status) {
108 ALOGE("LocklessCommandFifo: error %i unlocking for condition.", status);
109 }
110
111 return ret;
112 }
113
114