blob: c1d6f95e7fc969289c98774fe528db1ce200214c [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#ifndef AOS_COMMON_MUTEX_H_
2#define AOS_COMMON_MUTEX_H_
3
4#ifdef __VXWORKS__
5#include <semLib.h>
6#endif
7
8#include "aos/aos_core.h"
9#include "aos/common/macros.h"
10#include "aos/common/type_traits.h"
11
12namespace aos {
13
14// An abstraction of a mutex that has implementations both for the
15// atom and for the cRIO.
16// If there are multiple tasks or processes contending for the mutex,
17// higher priority ones will succeed in locking first,
18// and tasks of equal priorities have the same chance of getting the lock.
19// There is no priority inversion protection.
20class Mutex {
21 public:
22 // Creates an unlocked mutex.
23 Mutex();
24#ifdef __VXWORKS__
25 // Will not make sure that it is either locked or unlocked.
26 ~Mutex();
27#endif
28 // Locks the mutex. If it fails, it calls LOG(FATAL).
29 void Lock();
30 // Unlocks the mutex. Fails like Lock.
31 // Multiple unlocking might be considered failure.
32 void Unlock();
33 // Locks the mutex unless it is already locked.
34 // Returns whether it succeeded or not.
35 // Doesn't wait for the mutex to be unlocked if it is locked.
36 bool TryLock();
37
38 private:
39#ifdef __VXWORKS__
40 typedef SEM_ID ImplementationType;
41#else
42 typedef mutex ImplementationType;
43#endif
44 ImplementationType impl_;
45#ifdef __VXWORKS__
46 DISALLOW_COPY_AND_ASSIGN(Mutex);
47#endif
48};
49
50// A class that locks a Mutex when constructed and unlocks it when destructed.
51// Designed to be used as a local variable so that
52// the mutex will be unlocked when the scope is exited.
53// Should it fail for some reason, it dies with LOG(FATAL).
54class MutexLocker {
55 public:
56 explicit MutexLocker(Mutex *mutex) : mutex_(mutex) {
57 mutex_->Lock();
58 }
59 ~MutexLocker() {
60 mutex_->Unlock();
61 }
62
63 private:
64 Mutex *mutex_;
65 DISALLOW_COPY_AND_ASSIGN(MutexLocker);
66};
67
68} // namespace aos
69
70#endif // AOS_COMMON_MUTEX_H_