blob: ff953e40947a306bb48f11876fe62918048bf853 [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.
Brian Silverman6da04272014-05-18 18:47:48 -070033 // Multiple unlocking is undefined.
brians343bc112013-02-10 01:53:46 +000034 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.
brians343bc112013-02-10 01:53:46 +000058class MutexLocker {
59 public:
60 explicit MutexLocker(Mutex *mutex) : mutex_(mutex) {
61 mutex_->Lock();
62 }
63 ~MutexLocker() {
64 mutex_->Unlock();
65 }
66
67 private:
68 Mutex *mutex_;
69 DISALLOW_COPY_AND_ASSIGN(MutexLocker);
70};
Brian Silvermand41b4422013-09-01 14:02:33 -070071// The inverse of MutexLocker.
72class MutexUnlocker {
73 public:
74 explicit MutexUnlocker(Mutex *mutex) : mutex_(mutex) {
75 mutex_->Unlock();
76 }
77 ~MutexUnlocker() {
78 mutex_->Lock();
79 }
80
81 private:
82 Mutex *mutex_;
83 DISALLOW_COPY_AND_ASSIGN(MutexUnlocker);
84};
brians343bc112013-02-10 01:53:46 +000085
86} // namespace aos
87
88#endif // AOS_COMMON_MUTEX_H_