Line data Source code
1 : #pragma once 2 : 3 : #include "AP_HAL_Namespace.h" 4 : 5 : #include <AP_Common/AP_Common.h> 6 : 7 : #define HAL_SEMAPHORE_BLOCK_FOREVER 0 8 : 9 : class AP_HAL::Semaphore { 10 : public: 11 : 12 261081 : Semaphore() {} 13 : 14 : // do not allow copying 15 : CLASS_NO_COPY(Semaphore); 16 : 17 : virtual bool take(uint32_t timeout_ms) WARN_IF_UNUSED = 0 ; 18 : virtual bool take_nonblocking() WARN_IF_UNUSED = 0; 19 : 20 : // a variant that blocks forever 21 : #pragma GCC diagnostic push 22 : #pragma GCC diagnostic ignored "-Wunused-result" 23 5068796096 : virtual void take_blocking() { take(HAL_SEMAPHORE_BLOCK_FOREVER); }; 24 : #pragma GCC diagnostic pop 25 : 26 : virtual bool give() = 0; 27 52588 : virtual ~Semaphore(void) {} 28 : }; 29 : 30 : /* 31 : a method to make semaphores less error prone. The WITH_SEMAPHORE() 32 : macro will block forever for a semaphore, and will automatically 33 : release the semaphore when it goes out of scope 34 : 35 : All semaphores are recursive. This allows for the thread holding 36 : the semaphore to take it again. It must be released the same number 37 : of times it is taken. 38 : 39 : The WITH_SEMAPHORE() macro cannot be used with binary semaphores 40 : */ 41 : 42 : class WithSemaphore { 43 : public: 44 : WithSemaphore(AP_HAL::Semaphore *mtx, uint32_t line); 45 : WithSemaphore(AP_HAL::Semaphore &mtx, uint32_t line); 46 : 47 : ~WithSemaphore(); 48 : private: 49 : AP_HAL::Semaphore &_mtx; 50 : }; 51 : 52 : // From: https://stackoverflow.com/questions/19666142/why-is-a-level-of-indirection-needed-for-this-concatenation-macro 53 : #define WITH_SEMAPHORE( sem ) JOIN( sem, __AP_LINE__, __COUNTER__ ) 54 : 55 : #define JOIN( sem, line, counter ) _DO_JOIN( sem, line, counter ) 56 : #define _DO_JOIN( sem, line, counter ) WithSemaphore _getsem ## counter(sem, line) 57 : 58 : /* 59 : a binary semaphore 60 : */ 61 : class AP_HAL::BinarySemaphore { 62 : public: 63 : /* 64 : create a binary semaphore. initial_state determines if a wait() 65 : immediately after creation would block. If initial_state is true 66 : then it won't block, if initial_state is false it will block 67 : */ 68 4298 : BinarySemaphore(bool initial_state=false) {} 69 : 70 : // do not allow copying 71 : CLASS_NO_COPY(BinarySemaphore); 72 : 73 : virtual bool wait(uint32_t timeout_us) WARN_IF_UNUSED = 0 ; 74 : virtual bool wait_blocking() = 0; 75 0 : virtual bool wait_nonblocking() { return wait(0); } 76 : 77 : virtual void signal() = 0; 78 0 : virtual void signal_ISR() { signal(); } 79 : 80 1010 : virtual ~BinarySemaphore(void) {} 81 : };