01598164df5901377e9c24815475a299fb37d683
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / common / wait_handle.cpp
1 /*
2  * Copyright © 2012-2014 Canonical Ltd.
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU Lesser General Public License version 3,
6  * as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  * Authored by: Kevin DuBois <kevin.dubois@canonical.com>
17  *              Daniel van Vugt <daniel.van.vugt@canonical.com>
18  */
19
20 #include "anbox/common/wait_handle.h"
21
22 namespace anbox {
23 namespace common {
24 WaitHandle::WaitHandle()
25     : guard(), wait_condition(), expecting(0), received(0) {}
26
27 WaitHandle::~WaitHandle() {}
28
29 void WaitHandle::expect_result() {
30   std::lock_guard<std::mutex> lock(guard);
31
32   expecting++;
33 }
34
35 void WaitHandle::result_received() {
36   std::lock_guard<std::mutex> lock(guard);
37
38   received++;
39   wait_condition.notify_all();
40 }
41
42 void WaitHandle::wait_for_all()  // wait for all results you expect
43 {
44   std::unique_lock<std::mutex> lock(guard);
45
46   wait_condition.wait(lock, [&] { return received == expecting; });
47
48   received = 0;
49   expecting = 0;
50 }
51
52 void WaitHandle::wait_for_pending(std::chrono::milliseconds limit) {
53   std::unique_lock<std::mutex> lock(guard);
54
55   wait_condition.wait_for(lock, limit, [&] { return received == expecting; });
56 }
57
58 void WaitHandle::wait_for_one()  // wait for any single result
59 {
60   std::unique_lock<std::mutex> lock(guard);
61
62   wait_condition.wait(lock, [&] { return received != 0; });
63
64   --received;
65   --expecting;
66 }
67
68 bool WaitHandle::has_result() {
69   std::lock_guard<std::mutex> lock(guard);
70
71   return received > 0;
72 }
73
74 bool WaitHandle::is_pending() {
75   std::unique_lock<std::mutex> lock(guard);
76   return expecting > 0 && received != expecting;
77 }
78 }  // namespace common
79 }  // namespace anbox