6a161ae2b5c655caa25cf735d07c042397b2e64d
[iec.git] / src / type3_AndroidCloud / anbox-master / external / android-emugl / shared / emugl / common / mutex.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_MUTEX_H
16 #define EMUGL_MUTEX_H
17
18 #ifdef _WIN32
19 #  define WIN32_LEAN_AND_MEAN 1
20 #  include <windows.h>
21 #else
22 #  include <pthread.h>
23 #endif
24
25 namespace emugl {
26
27 class ConditionVariable;
28
29 // Simple wrapper class for mutexes.
30 class Mutex {
31 public:
32     // Constructor.
33     Mutex() {
34 #ifdef _WIN32
35         ::InitializeCriticalSection(&mLock);
36 #else
37         ::pthread_mutex_init(&mLock, NULL);
38 #endif
39     }
40
41     // Destructor.
42     ~Mutex() {
43 #ifdef _WIN32
44         ::DeleteCriticalSection(&mLock);
45 #else
46         ::pthread_mutex_destroy(&mLock);
47 #endif
48     }
49
50     // Acquire the mutex.
51     void lock() {
52 #ifdef _WIN32
53       ::EnterCriticalSection(&mLock);
54 #else
55       ::pthread_mutex_lock(&mLock);
56 #endif
57     }
58
59     // Release the mutex.
60     void unlock() {
61 #ifdef _WIN32
62        ::LeaveCriticalSection(&mLock);
63 #else
64        ::pthread_mutex_unlock(&mLock);
65 #endif
66     }
67
68     // Helper class to lock / unlock a mutex automatically on scope
69     // entry and exit.
70     class AutoLock {
71     public:
72         AutoLock(Mutex& mutex) : mMutex(&mutex) {
73             mMutex->lock();
74         }
75
76         ~AutoLock() {
77             mMutex->unlock();
78         }
79     private:
80         Mutex* mMutex;
81     };
82
83 private:
84 #ifdef _WIN32
85     CRITICAL_SECTION mLock;
86 #else
87     friend class ConditionVariable;
88     pthread_mutex_t mLock;
89 #endif
90
91 };
92
93 }  // namespace emugl
94
95 #endif  // EMUGL_MUTEX_H