blob: a22df4ec1d392cd7b9b71dbde4168e7c45eb1959 [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
brians343bc112013-02-10 01:53:46 +00008#include "aos/common/macros.h"
9#include "aos/common/type_traits.h"
Brian Silverman14fd0fb2014-01-14 21:42:01 -080010#include "aos/linux_code/ipc_lib/aos_sync.h"
brians343bc112013-02-10 01:53:46 +000011
12namespace aos {
13
Brian Silverman08661c72013-09-01 17:24:38 -070014class Condition;
15
Brian Silverman14fd0fb2014-01-14 21:42:01 -080016// An abstraction of a mutex that has implementations both for
17// linux and for the cRIO.
brians343bc112013-02-10 01:53:46 +000018// If there are multiple tasks or processes contending for the mutex,
19// higher priority ones will succeed in locking first,
20// and tasks of equal priorities have the same chance of getting the lock.
21// There is no priority inversion protection.
22class Mutex {
23 public:
24 // Creates an unlocked mutex.
25 Mutex();
26#ifdef __VXWORKS__
27 // Will not make sure that it is either locked or unlocked.
28 ~Mutex();
29#endif
30 // Locks the mutex. If it fails, it calls LOG(FATAL).
31 void Lock();
32 // Unlocks the mutex. Fails like Lock.
33 // Multiple unlocking might be considered failure.
34 void Unlock();
35 // Locks the mutex unless it is already locked.
36 // Returns whether it succeeded or not.
37 // Doesn't wait for the mutex to be unlocked if it is locked.
38 bool TryLock();
39
40 private:
41#ifdef __VXWORKS__
42 typedef SEM_ID ImplementationType;
43#else
44 typedef mutex ImplementationType;
45#endif
46 ImplementationType impl_;
Brian Silverman08661c72013-09-01 17:24:38 -070047
48 friend class Condition; // for access to impl_
49
brians343bc112013-02-10 01:53:46 +000050#ifdef __VXWORKS__
51 DISALLOW_COPY_AND_ASSIGN(Mutex);
52#endif
53};
54
55// A class that locks a Mutex when constructed and unlocks it when destructed.
56// Designed to be used as a local variable so that
57// the mutex will be unlocked when the scope is exited.
58// Should it fail for some reason, it dies with LOG(FATAL).
59class MutexLocker {
60 public:
61 explicit MutexLocker(Mutex *mutex) : mutex_(mutex) {
62 mutex_->Lock();
63 }
64 ~MutexLocker() {
65 mutex_->Unlock();
66 }
67
68 private:
69 Mutex *mutex_;
70 DISALLOW_COPY_AND_ASSIGN(MutexLocker);
71};
Brian Silvermand41b4422013-09-01 14:02:33 -070072// The inverse of MutexLocker.
73class MutexUnlocker {
74 public:
75 explicit MutexUnlocker(Mutex *mutex) : mutex_(mutex) {
76 mutex_->Unlock();
77 }
78 ~MutexUnlocker() {
79 mutex_->Lock();
80 }
81
82 private:
83 Mutex *mutex_;
84 DISALLOW_COPY_AND_ASSIGN(MutexUnlocker);
85};
brians343bc112013-02-10 01:53:46 +000086
87} // namespace aos
88
89#endif // AOS_COMMON_MUTEX_H_