97c399b0277021a8f7326da57f93edaa5d0c8183
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / 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 "anbox/common/message_channel.h"
16
17 namespace anbox {
18 namespace common {
19 MessageChannelBase::MessageChannelBase(size_t capacity) : pos_(0U),
20                                                           count_(0U),
21                                                           capacity_(capacity),
22                                                           lock_(),
23                                                           can_read_(),
24                                                           can_write_() {}
25
26 MessageChannelBase::~MessageChannelBase() {}
27
28 size_t MessageChannelBase::before_write() {
29   std::unique_lock<std::mutex> l(lock_, std::defer_lock);
30   lock_.lock();
31
32   while (count_ >= capacity_)
33     can_write_.wait(l);
34
35   size_t result = pos_ + count_;
36   if (result >= capacity_)
37     result -= capacity_;
38
39   return result;
40 }
41
42 void MessageChannelBase::after_write() {
43   count_++;
44   can_read_.notify_one();
45   lock_.unlock();
46 }
47
48 size_t MessageChannelBase::before_read() {
49   std::unique_lock<std::mutex> l(lock_, std::defer_lock);
50   lock_.lock();
51   while (count_ == 0)
52     can_read_.wait(l);
53   return pos_;
54 }
55
56 void MessageChannelBase::after_read() {
57   if (++pos_ == capacity_)
58     pos_ = 0U;
59   count_--;
60   can_write_.notify_one();
61   lock_.unlock();
62 }
63 }  // namespace common
64 }  // namespace anbox