CallbackProtector.cpp revision 485a038f9f0f898227b8ab4218e94c5d56b6ed0b
1/*
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 "CallbackProtector.h"
18
19#include <media/stagefright/foundation/ADebug.h>
20
21//--------------------------------------------------------------------------------------------------
22namespace android {
23
24
25CallbackProtector::CallbackProtector() : RefBase(),
26        mSafeToEnterCb(true),
27        mCbCount(0) {
28}
29
30
31CallbackProtector::~CallbackProtector() {
32
33}
34
35
36// static
37bool CallbackProtector::enterCbIfOk(const sp<CallbackProtector> &protector) {
38    if (protector != 0) {
39        return protector->enterCb();
40    } else {
41        return false;
42    }
43}
44
45
46bool CallbackProtector::enterCb() {
47    Mutex::Autolock _l(mLock);
48    if (mSafeToEnterCb) {
49        mCbCount++;
50    }
51    return mSafeToEnterCb;
52}
53
54
55void CallbackProtector::exitCb() {
56    Mutex::Autolock _l(mLock);
57
58    CHECK(mCbCount > 0);
59    mCbCount--;
60
61    if (mCbCount == 0) {
62        mCbExitedCondition.broadcast();
63    }
64}
65
66
67void CallbackProtector::requestCbExitAndWait() {
68    Mutex::Autolock _l(mLock);
69    mSafeToEnterCb = false;
70    while (mCbCount) {
71        mCbExitedCondition.wait(mLock);
72    }
73}
74
75
76} // namespace android
77