TYPE3
[iec.git] / src / type3_AndroidCloud / anbox-master / external / android-emugl / shared / emugl / common / condition_variable.h
1 // Copyright (C) 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 #ifndef EMUGL_CONDITION_VARIABLE_H
16 #define EMUGL_CONDITION_VARIABLE_H
17
18 #include "emugl/common/mutex.h"
19 #include "emugl/common/pod_vector.h"
20
21 #ifdef _WIN32
22 #include <windows.h>
23 #else
24 #include <pthread.h>
25 #endif
26
27 namespace emugl {
28
29 // A class that implements a condition variable, which can be used in
30 // association with a Mutex to blocking-wait for specific conditions.
31 // Useful to implement various synchronization data structures.
32 // For an example, see ::emugl::MessageChannel.
33 class ConditionVariable {
34 public:
35 #ifdef _WIN32
36
37     // Default constructor.
38     ConditionVariable();
39
40     // Destructor.
41     ~ConditionVariable();
42
43     // Wait until the condition variable is signaled. Note that spurious
44     // wakeups are always a possibility, so always check the condition
45     // in a loop, i.e. do:
46     //
47     //    while (!condition) { condVar.wait(&lock); }
48     //
49     // instead of:
50     //
51     //    if (!condition) { condVar.wait(&lock); }
52     //
53     void wait(Mutex* userLock);
54
55     // Signal that a condition was reached. This will wake at most one
56     // waiting thread that is blocked on wait().
57     void signal();
58
59 private:
60     PodVector<HANDLE> mWaiters;
61     Mutex mLock;
62
63 #else  // !_WIN32
64
65     // Note: on Posix systems, make it a naive wrapper around pthread_cond_t.
66
67     ConditionVariable() {
68         pthread_cond_init(&mCond, NULL);
69     }
70
71     ~ConditionVariable() {
72         pthread_cond_destroy(&mCond);
73     }
74
75     void wait(Mutex* userLock) {
76         pthread_cond_wait(&mCond, &userLock->mLock);
77     }
78
79     void signal() {
80         pthread_cond_signal(&mCond);
81     }
82
83 private:
84     pthread_cond_t mCond;
85
86 #endif  // !_WIN32
87 };
88
89 }  // namespace emugl
90
91 #endif  // EMUGL_CONDITION_VARIABLE_H