1 : /*
2 : * Copyright 2010 The Native Client Authors. All rights reserved.
3 : * Use of this source code is governed by a BSD-style license that can
4 : * be found in the LICENSE file.
5 : */
6 :
7 :
8 : // This module defines the interface for using platform specific mutexes.
9 : // It is expected that the Allocation function will return NULL on any
10 : // failure instead of throwing an exception. This module is expected
11 : // to throw a std::exception when an unexpected OS error is encoutered.
12 : //
13 : // The mutex is owned by a single thread at a time. The thread that
14 : // owns the mutex is free to call Lock multiple times, however it must
15 : // call Unlock the same number of times to release the lock.
16 : #ifndef NATIVE_CLIENT_PORT_MUTEX_H_
17 : #define NATIVE_CLIENT_PORT_MUTEX_H_ 1
18 :
19 : #include <assert.h>
20 : #include <stddef.h>
21 :
22 : namespace port {
23 :
24 7 : class IMutex {
25 : public:
26 : virtual void Lock() = 0; // Block until the mutex is taken
27 : virtual void Unlock() = 0; // Unlock the mutext
28 : virtual bool Try() = 0; // Try to lock, but return immediately
29 :
30 : static IMutex *Allocate(); // Allocate a mutex
31 : static void Free(IMutex *mtx); // Free a mutex
32 :
33 : protected:
34 0 : virtual ~IMutex() {} // Prevent delete of base pointer
35 : };
36 :
37 :
38 : // MutexLock
39 : // A MutexLock object will lock on construction and automatically
40 : // unlock on destruction of the object as the object goes out of scope.
41 : class MutexLock {
42 : public:
43 28 : explicit MutexLock(IMutex *mutex) : mutex_(mutex) {
44 28 : assert(NULL != mutex_);
45 28 : mutex_->Lock();
46 28 : }
47 28 : ~MutexLock() {
48 28 : mutex_->Unlock();
49 28 : }
50 :
51 : private:
52 : IMutex *mutex_;
53 : MutexLock(const MutexLock&);
54 : MutexLock &operator=(const MutexLock&);
55 : };
56 :
57 :
58 : } // namespace port
59 :
60 : #endif // NATIVE_CLIENT_PORT_MUTEX_H_
61 :
|