• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // Simple wrapper class for mutexes.
28 class Mutex {
29 public:
30     // Constructor.
Mutex()31     Mutex() {
32 #ifdef _WIN32
33         ::InitializeCriticalSection(&mLock);
34 #else
35         ::pthread_mutex_init(&mLock, NULL);
36 #endif
37     }
38 
39     // Destructor.
~Mutex()40     ~Mutex() {
41 #ifdef _WIN32
42         ::DeleteCriticalSection(&mLock);
43 #else
44         ::pthread_mutex_destroy(&mLock);
45 #endif
46     }
47 
48     // Acquire the mutex.
lock()49     void lock() {
50 #ifdef _WIN32
51       ::EnterCriticalSection(&mLock);
52 #else
53       ::pthread_mutex_lock(&mLock);
54 #endif
55     }
56 
57     // Release the mutex.
unlock()58     void unlock() {
59 #ifdef _WIN32
60        ::LeaveCriticalSection(&mLock);
61 #else
62        ::pthread_mutex_unlock(&mLock);
63 #endif
64     }
65 
66     // Helper class to lock / unlock a mutex automatically on scope
67     // entry and exit.
68     class AutoLock {
69     public:
AutoLock(Mutex & mutex)70         AutoLock(Mutex& mutex) : mMutex(&mutex) {
71             mMutex->lock();
72         }
73 
~AutoLock()74         ~AutoLock() {
75             mMutex->unlock();
76         }
77     private:
78         Mutex* mMutex;
79     };
80 
81 private:
82 #ifdef _WIN32
83     CRITICAL_SECTION mLock;
84 #else
85     pthread_mutex_t mLock;
86 #endif
87 
88 };
89 
90 }  // namespace emugl
91 
92 #endif  // EMUGL_MUTEX_H
93