blob: 251eb3c5ae7d287f79c811b5c9ab57fdf18bbc37 [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).
Austin Schuhf4b194e2014-09-21 10:26:41 -070031 // Returns false.
32 bool Lock();
brians343bc112013-02-10 01:53:46 +000033 // Unlocks the mutex. Fails like Lock.
Brian Silverman6da04272014-05-18 18:47:48 -070034 // Multiple unlocking is undefined.
brians343bc112013-02-10 01:53:46 +000035 void Unlock();
36 // Locks the mutex unless it is already locked.
37 // Returns whether it succeeded or not.
38 // Doesn't wait for the mutex to be unlocked if it is locked.
39 bool TryLock();
40
41 private:
42#ifdef __VXWORKS__
43 typedef SEM_ID ImplementationType;
44#else
45 typedef mutex ImplementationType;
46#endif
47 ImplementationType impl_;
Brian Silverman08661c72013-09-01 17:24:38 -070048
49 friend class Condition; // for access to impl_
50
brians343bc112013-02-10 01:53:46 +000051#ifdef __VXWORKS__
52 DISALLOW_COPY_AND_ASSIGN(Mutex);
53#endif
54};
55
56// A class that locks a Mutex when constructed and unlocks it when destructed.
57// Designed to be used as a local variable so that
58// the mutex will be unlocked when the scope is exited.
brians343bc112013-02-10 01:53:46 +000059class 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_