TYPE3
[iec.git] / src / type3_AndroidCloud / anbox-master / external / android-emugl / shared / emugl / common / message_channel.cpp
1 // Copyright 2014 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "emugl/common/message_channel.h"
16
17 namespace emugl {
18
19 MessageChannelBase::MessageChannelBase(size_t capacity) :
20         mPos(0U),
21         mCount(0U),
22         mCapacity(capacity),
23         mLock(),
24         mCanRead(),
25         mCanWrite() {}
26
27 MessageChannelBase::~MessageChannelBase() {}
28
29 size_t MessageChannelBase::beforeWrite() {
30     mLock.lock();
31     while (mCount >= mCapacity) {
32         mCanWrite.wait(&mLock);
33     }
34     size_t result = mPos + mCount;
35     if (result >= mCapacity) {
36         result -= mCapacity;
37     }
38     return result;
39 }
40
41 void MessageChannelBase::afterWrite() {
42     mCount++;
43     mCanRead.signal();
44     mLock.unlock();
45 }
46
47 size_t MessageChannelBase::beforeRead() {
48     mLock.lock();
49     while (mCount == 0) {
50         mCanRead.wait(&mLock);
51     }
52     return mPos;
53 }
54
55 void MessageChannelBase::afterRead() {
56     if (++mPos == mCapacity) {
57         mPos = 0U;
58     }
59     mCount--;
60     mCanWrite.signal();
61     mLock.unlock();
62 }
63
64 }  // namespace emugl